代码之家  ›  专栏  ›  技术社区  ›  pierrotlefou

如何返回空tr1::shared_ptr并测试它是否为空

  •  2
  • pierrotlefou  · 技术社区  · 14 年前

    我有一个功能 getA() 签字如下:

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

    我想返回一个空指针 GET() 在同样的情况下;同时,作为 Class B ,我需要测试 GET() 在使用前为空。我该怎么做?

    1 回复  |  直到 9 年前
        1
  •  5
  •   Kirill V. Lyadvinsky    14 年前

    注意 A::Ptr 在您的示例中是私有的。你应该把它修好。

    返回空指针:

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

    检查:

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