views:

53

answers:

1

Hi,

I have a function getA() with following signature :

class A {  
public:
 typedef std::tr1::shared_ptr <A> Ptr;
 //other member functions.... 
 };
class B {
 pubic:
 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?

+3  A: 

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 */ }
}
Kirill V. Lyadvinsky