在shared_ptr的自定义删除器中检查nullptr是否有意义? [英] Does it make sense to check for nullptr in custom deleter of shared_ptr?
问题描述
我看过一些使用 std :: shared_ptr
和自定义删除器的代码,这些删除器测试nullptr的参数,例如 MyClass
具有 close()
方法,并使用某些 CreateMyClass
构造:
I've seen some code that uses std::shared_ptr
with a custom deleter that test the argument for nullptr, for example, MyClass
which has a close()
method and is constructed with some CreateMyClass
:
auto pMyClass = std::shared_ptr<MyClass>(CreateMyClass(),
[](MyClass* ptr)
{
if(ptr)
ptr->close();
});
测试 ptr
是否有意义删除器中是否为空?
这会发生吗?
Does it make sense to test ptr
for null-ness in the deleter?
Can this happen? how?
推荐答案
构造函数 std :: shared_ptr< T> :: shared_ptr(Y * p)
要求删除p
是有效操作。当 p
等于 nullptr
时,此操作有效。
The constructor std::shared_ptr<T>::shared_ptr(Y*p)
has the requirement that delete p
is a valid operation. This is a valid operation when p
equals nullptr
.
构造函数 std :: shared_ptr< T> :: shared_ptr(Y * p,Del del)
要求 del(p)
是有效操作。
The constructor std::shared_ptr<T>::shared_ptr(Y*p, Del del)
has the requirement that del(p)
is a valid operation.
如果自定义删除器无法处理 p
等于 nullptr
,则在 shared_ptr $ c的构造函数中传递空
p
是无效的$ c>。
If your custom deleter cannot handle p
being equal to nullptr
then it is not valid to pass a null p
in the constructor of shared_ptr
.
您提供的示例构造函数可以更好地呈现,因此:
The constructor you offer as an example can be better presented, thus:
#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现在不可能拥有空对象。
Note that it is now not possible for the shared_ptr to own a null object.
这篇关于在shared_ptr的自定义删除器中检查nullptr是否有意义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!