I'm using reset()
as a default value for my shared_pointer (equivalent to a NULL
).
But how do I check if开发者_如何学Python the shared_pointer is 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() ?
}
Use:
if (!blah)
{
//This checks if the object was reset() or never initialized
}
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.
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:
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.
As shown in boost::shared_ptr<>
's documentation, there exists a boolean conversion operator:
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
:
if (!blah) {
// this has the semantics you want
}
精彩评论