c++ - 在 shared_ptr 的自定义删除器中检查 nullptr 是否有意义?

标签 c++ c++11 shared-ptr

我见过一些代码使用 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)要求 delete p是一个有效的操作。这是一个有效的操作 p等于 nullptr .

构造函数std::shared_ptr<T>::shared_ptr(Y*p, Del del)要求 del(p)是一个有效的操作。

如果您的自定义删除器无法处理 p等于 nullptr那么传递一个空值 p 是无效的在 shared_ptr 的构造函数中.

您作为示例提供的构造函数可以更好地呈现,因此:

#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 现在不可能拥有空对象。

关于c++ - 在 shared_ptr 的自定义删除器中检查 nullptr 是否有意义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42962515/

相关文章:

c++ - 将移位的无符号数字用作数组的索引号是一个好习惯

c++ - 如何从枚举类型中获取 std::string?

c++ - Boost.Python 和 std::shared_ptr 的多态行为

c++ - 在 shared_ptr 中使用 deallocator & allocator

c++ - 为什么移动构造函数需要使用 "rvalue reference"?

c++ - QGraphicsWidget 上的上下文菜单

c++ - "multiple definition of"错误的奇怪类型

c++ - `class template Example<int>;` 语句对 C++11 意味着什么?

c++ - 哪些 IDE 和文本编辑器可以推断在 C++11 中使用 auto 关键字声明的变量类型

c++ - std::shared_ptr 中的错误?