gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 22:58:50 28 4
gpt4 key购买 nike

我见过一些代码使用 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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com