【问题标题】:boost Shared_pointer NULL提升 Shared_pointer NULL
【发布时间】:2011-08-02 09:41:36
【问题描述】:
我使用reset() 作为我的shared_pointer 的默认值(相当于NULL)。
但是如何检查 shared_pointer 是否为NULL?
这会返回正确的值吗?
boost::shared_ptr<Blah> blah;
blah.reset()
if (blah == NULL)
{
//Does this check if the object was reset() ?
}
【问题讨论】:
标签:
c++
boost
shared-ptr
smart-pointers
【解决方案1】:
用途:
if (!blah)
{
//This checks if the object was reset() or never initialized
}
【解决方案2】:
if blah == NULL 可以正常工作。有些人更喜欢它而不是作为布尔测试(if !blah),因为它更明确。其他人更喜欢后者,因为它更短。
【解决方案3】:
您可以将指针作为布尔值进行测试:如果它是非空的,它将评估为true,如果它是空的,它将评估为false:
if (!blah)
boost::shared_ptr 和 std::tr1::shared_ptr 都实现了安全布尔惯用语,而 C++0x 的 std::shared_ptr 实现了显式的 bool 转换运算符。这些允许 shared_ptr 在某些情况下用作布尔值,类似于普通指针可以用作布尔值。
【解决方案4】:
如boost::shared_ptr<>的documentation所示,存在布尔转换运算符:
explicit operator bool() const noexcept;
// or pre-C++11:
operator unspecified-bool-type() const; // never throws
所以只需使用shared_ptr<>,就好像它是bool:
if (!blah) {
// this has the semantics you want
}