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

2024-03-12

我见过一些使用的代码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 equals nullptr.

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

如果您的自定义删除器无法处理p等于nullptr那么传递 null 是无效的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 现在不可能拥有空对象。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在shared_ptr的自定义删除器中检查nullptr是否有意义? 的相关文章

随机推荐