boost Shared_pointer NULL
Solution 1
Use:
if (!blah)
{
//This checks if the object was reset() or never initialized
}
Solution 2
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.
Solution 3
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.
Solution 4
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
}
Yochai Timmer
"Yes, but your program doesn't work. If mine doesn't have to work, I can make it run instantly and take up no memory. "
Updated on July 27, 2022Comments
-
Yochai Timmer almost 2 years
I'm using
reset()
as a default value for my shared_pointer (equivalent to aNULL
).But how do I check if 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() ? }