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)
您可以将指针作为布尔值进行测试:它将评估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在某些情况下用作布尔值,类似于普通指针可以用作布尔值的方式.
如在所示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)
| 归档时间: |
|
| 查看次数: |
32585 次 |
| 最近记录: |