pierrotlefou
pierrotlefou

Reputation: 40721

how to return an null tr1::shared_ptr and test if it is null

I have a function getA() with the following signature:

class A {  
public:
 typedef std::tr1::shared_ptr <A> Ptr;
 //other member functions.... 
};

class B {
public:
 A::Ptr getA();
};

And, I want to return an empty pointer in getA() in same case; Also, as a user of Class B , I need to test if the return value of getA() is null before using it. How should I do it?

Upvotes: 2

Views: 5718

Answers (1)

Kirill V. Lyadvinsky
Kirill V. Lyadvinsky

Reputation: 99585

Note that A::Ptr is private in your sample. You should fix it.

To return an empty pointer:

A::Ptr B::getA()
{
   // ...
   if ( something ) return A::Ptr(); // return empty shared_ptr
   else return something_else;
}

To check it:

int test()
{
  B b;
  A::Ptr p = b.getA(); // getA is private too, but suppose it will not
  if ( p ) { /* do something */ }
}

Upvotes: 5

Related Questions