我看到一些代码,使用std :: shared_ptr与一个自定义的删除器来测试nullptr的参数,例如MyClass,它有一个close()方法,并用一些CreateMyClass构造:
auto pMyClass = std::shared_ptr<MyClass>(CreateMyClass(),[](MyClass* ptr) { if(ptr) ptr->close(); });
在删除器中测试ptr的空值是否有意义?
这可能发生吗?怎么样?
解决方法
构造函数std :: shared_ptr< T> :: shared_ptr(Y * p)要求删除p是有效的操作.当p等于nullptr时,这是一个有效的操作.
构造函数std :: shared_ptr< T> :: shared_ptr(Y * p,Del del)要求del(p)是有效的操作.
如果您的自定义删除器无法处理p等于nullptr,那么在shared_ptr的构造函数中传递null p是无效的.
您提供的构造函数可以更好地呈现,因此:
#include <memory> struct MyClass { void open() { // note - may throw }; void close() noexcept { // pre - is open } }; struct Closer { void operator()(MyClass* p) const noexcept { p->close(); delete p; // or return to pool,etc } }; auto CreateMyClass() -> std::unique_ptr<MyClass,Closer> { // first construct with normal deleter auto p1 = std::make_unique<MyClass>(); // in case this throws an exception. p1->open(); // Now it's open,we need a more comprehensive deleter auto p = std::unique_ptr<MyClass,Closer> { p1.release(),Closer() }; return p; } int main() { auto sp = std::shared_ptr<MyClass>(CreateMyClass()); }
请注意,shared_ptr现在不可能拥有一个空对象.
原文地址:https://www.jb51.cc/c/113340.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。