如何返回null tr​​1 :: shared_ptr并测试它是否为null

pie*_*fou 2 c++ smart-pointers

我有一个getA()具有以下签名的函数:

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

class B {
public:
 A::Ptr getA();
};
Run Code Online (Sandbox Code Playgroud)

并且,我希望getA()在相同的情况下返回一个空指针; 另外,作为用户Class B,我需要getA()在使用之前测试返回值是否为null.我该怎么办?

Kir*_*sky 5

请注意,A::Ptr样本中是私有的.你应该解决它.

要返回空指针:

A::Ptr B::getA()
{
   // ...
   if ( something ) return A::Ptr(); // return empty shared_ptr
   else return something_else;
}
Run Code Online (Sandbox Code Playgroud)

检查一下:

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