29

I'm using reset() as a default value for my shared_pointer (equivalent to a NULL).

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() ?
}
Null
  • 1,950
  • 9
  • 30
  • 33
Yochai Timmer
  • 48,127
  • 24
  • 147
  • 185

4 Answers4

36

Use:

if (!blah)
{
    //This checks if the object was reset() or never initialized
}
Ralph
  • 5,154
  • 1
  • 21
  • 19
11

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.

ymett
  • 2,425
  • 14
  • 22
9

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.

James McNellis
  • 348,265
  • 75
  • 913
  • 977
7

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
}
ildjarn
  • 62,044
  • 9
  • 127
  • 211