提升Shared_pointer NULL

Yoc*_*mer 27 c++ boost smart-pointers shared-ptr

reset()用作shared_pointer的默认值(相当于a NULL).

但是如何检查shared_pointer是否是NULL

这会返回正确的价值吗?

boost::shared_ptr<Blah> blah;
blah.reset()
if (blah == NULL) 
{
    //Does this check if the object was reset() ?
}
Run Code Online (Sandbox Code Playgroud)

Ral*_*lph 34

使用:

if (!blah)
{
    //This checks if the object was reset() or never initialized
}
Run Code Online (Sandbox Code Playgroud)


yme*_*ett 11

if blah == NULL会很好的.有些人更喜欢它作为bool(if !blah)进行测试,因为它更明确.其他人更喜欢后者,因为它更短.


Jam*_*lis 9

您可以将指针作为布尔值进行测试:它将评估true它是否为非null且false是否为null:

if (!blah)
Run Code Online (Sandbox Code Playgroud)

boost::shared_ptr并且std::tr1::shared_ptr都实现了safe-bool习语,而C++ 0x std::shared_ptr实现了一个显式bool转换运算符.这些允许shared_ptr在某些情况下用作布尔值,类似于普通指针可以用作布尔值的方式.


ild*_*arn 7

如在所示boost::shared_ptr<>文档中,存在一个布尔转换运算符:

explicit operator bool() const noexcept;
// or pre-C++11:
operator unspecified-bool-type() const; // never throws
Run Code Online (Sandbox Code Playgroud)

所以简单地使用shared_ptr<>就像它是bool:

if (!blah) {
    // this has the semantics you want
}
Run Code Online (Sandbox Code Playgroud)