C++ 提升 Shared_pointer NULL
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5610527/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
boost Shared_pointer NULL
提问by Yochai Timmer
I'm using reset()
as a default value for my shared_pointer (equivalent to a NULL
).
我将其reset()
用作我的 shared_pointer (相当于 a NULL
)的默认值。
But how do I check if the shared_pointer is NULL
?
但是如何检查 shared_pointer 是否为NULL
?
Will this return the right value ?
这会返回正确的值吗?
boost::shared_ptr<Blah> blah;
blah.reset()
if (blah == NULL)
{
//Does this check if the object was reset() ?
}
回答by Ralph
Use:
用:
if (!blah)
{
//This checks if the object was reset() or never initialized
}
回答by ymett
if blah == NULL
will work fine. Some people would prefer it over testing as a bool (if !blah
) because it's more explicit. Others prefer the latter because it's shorter.
if blah == NULL
会正常工作。有些人更喜欢将其作为 bool ( if !blah
)进行测试,因为它更明确。其他人更喜欢后者,因为它更短。
回答by James McNellis
You can just test the pointer as a boolean: it will evaluate to true
if it is non-null and false
if it is null:
您可以将指针作为布尔值进行测试:它将评估true
它是否为非空以及false
是否为空:
if (!blah)
boost::shared_ptr
and std::tr1::shared_ptr
both implement the safe-bool idiom and C++0x's std::shared_ptr
implements an explicit bool
conversion operator. These allow a shared_ptr
be used as a boolean in certain circumstances, similar to how ordinary pointers can be used as a boolean.
boost::shared_ptr
并且std::tr1::shared_ptr
都实现了安全布尔习语,而 C++0xstd::shared_ptr
实现了显式bool
转换运算符。这些允许shared_ptr
在某些情况下将 a用作布尔值,类似于普通指针如何用作布尔值。
回答by ildjarn
As shown in boost::shared_ptr<>
's documentation, there exists a boolean conversion operator:
如在所示boost::shared_ptr<>
的文档中,存在一个布尔转换运算符:
explicit operator bool() const noexcept;
// or pre-C++11:
operator unspecified-bool-type() const; // never throws
So simply use the shared_ptr<>
as though it were a bool
:
所以简单地使用,shared_ptr<>
就好像它是一个bool
:
if (!blah) {
// this has the semantics you want
}