开发者

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 ge开发者_如何学PythontA() 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?


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 */ }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜