在C++中向基类返回shared_ptr



我有以下问题。我有一个类,它有函数

std::shared_ptr<IBaseInterface> getBaseInterface()
{
return m_spBase;
}

我还有以下内容:

private:
std::shared_ptr<IBaseInterface> m_spBase;
XMLReader* m_xmlReader;
std::unique_ptr<DerivedInterface> m_xmlInterface;

这里的事情是DerivedInterface继承自IBaseInterface,所以从外面看,它应该是可见的IBaseInterface。我还应该提到,m_xmlInterface在这里不必是一个指针(唯一/不唯一(。此外,DerivedInterface 是一个具体的类,它具有以下构造函数(这对于我的问题可能不太重要(:

DerivedInterface( XMLReader* pxmlReader );

IBaseInterface 只是一个纯抽象类,它有一些 DerivedInterface 定义的纯虚函数。

现在,我想创建一个衍生接口的实例并使用getBaseInterface将其作为IBaseInterface返回,这是我的主要观点。我尝试在类的构造函数中做这样的事情:

m_xmlInterface = std::unique_ptr<DerivedInterface>(
new DerivedInterface( m_xmlReader ) );
m_spBase = std::move( m_xmlInterface );

但这不起作用(我假设你不能将一种类型的指针移动到另一种类型的指针,即使一个指针指向的类从另一个指针继承(。如果有人就如何做到这一点提出任何建议,我将很高兴。

首先考虑要实现的目标的所有权语义,并向类和函数的用户宣传,然后选择适合它的实现和类型。

  1. 从你写的内容来看,你似乎想在你的类的对象和它的用户之间共享m_xmlInterface的所有权。这意味着,如果用户获得接口,当类的对象消失时,它仍然拥有它。在这种情况下,您应该将其存储为类中的共享指针,并将其作为共享指针返回。在这种情况下,您将拥有:

    std::shared_ptr<DerivedInterface> m_xmlInterface;
    

    并且:简单地说:

    std::shared_ptr<IBaseInterface> getBaseInterface()
    {
    return m_xmlInterface;
    }
    

    无需通过另一个变量。下面是一个完整的示例,显示了这项工作:

    #include <memory>
    struct A {};
    struct B : public A {};
    class Foo {
    public:
    Foo() {}
    std::shared_ptr<A> get() { return mB; }
    private:
    std::shared_ptr<B> mB;
    };
    int main() {
    auto foo = Foo{};
    auto a = foo.get();
    }
    
  2. 如果您希望所有权严格保留在您的类中,您可以将其存储为unique_ptr。然后,您可以授予访问权限的唯一方法是返回原始指针或引用(可能更可取(,除非您希望使类可以放弃所有权,在这种情况下,您应该使用move.那么最好不要返回共享指针,但仍然是一个唯一的指针,这使调用者可以自由决定是否要在之后共享它。在这种情况下,您将拥有:

    std::unique_ptr<DerivedInterface> m_xmlInterface;
    

    和:

    std::unique_ptr<IBaseInterface> getBaseInterface()
    {
    return std::move(m_xmlInterface);
    }
    

    注意:在任何人调用这个函数之后,你的类不能再使用m_xmlInterface,它失去了它的所有所有权。

最新更新