C++ 将共享的ptr返回到C+中的基类+;
我有以下问题。我有一个类,它有函数C++ 将共享的ptr返回到C+中的基类+;,c++,C++,我有以下问题。我有一个类,它有函数 std::shared_ptr<IBaseInterface> getBaseInterface() { return m_spBase; } IBaseInterface只是一个纯抽象类,它有一些DerivedInterface定义的纯虚拟函数 现在,我想创建一个DerivedInterface实例,并使用getBaseInterface将其作为IBaseInterface返回,这是我的主要观点。我尝试在类的构造函数中执
std::shared_ptr<IBaseInterface> getBaseInterface()
{
return m_spBase;
}
IBaseInterface只是一个纯抽象类,它有一些DerivedInterface定义的纯虚拟函数
现在,我想创建一个DerivedInterface实例,并使用getBaseInterface
将其作为IBaseInterface
返回,这是我的主要观点。我尝试在类的构造函数中执行以下操作:
m_xmlInterface = std::unique_ptr<DerivedInterface>(
new DerivedInterface( m_xmlReader ) );
m_spBase = std::move( m_xmlInterface );
m_xmlInterface=std::unique\u ptr(
新的DerivedInterface(m_xmlReader));
m_spBase=std::move(m_xmlInterface);
但这不起作用(我假设您不能将一种类型的指针移动到另一种类型的指针,即使一个指针指向的类继承了另一个指针)。如果有人对如何做到这一点提出任何建议,我将非常高兴。首先考虑您想要实现的内容的所有权语义,并向您的类和函数的用户发布,然后选择适合它的实现和类型
m_xmlInterface
的所有权。也就是说,如果用户获得了接口,当类的对象离开时,它仍然拥有它。在这种情况下,您应该将其作为共享指针存储在类中,并将其作为共享指针返回。在这种情况下,您可能会:
std::shared_ptr<DerivedInterface> m_xmlInterface;
std::unique_ptr<DerivedInterface> m_xmlInterface;
以及:
std::unique_ptr getBaseInterface()
{
返回std::move(m_xmlInterface);
}
不管有多大,注意:在任何人调用此函数后,您的类都不能再使用m_xmlInterface
,它失去了对它的所有所有权首先考虑您想要实现的内容的所有权语义,并向您的类和函数的用户发布,然后选择适合它的实现和类型
m_xmlInterface
的所有权。也就是说,如果用户获得了接口,当类的对象离开时,它仍然拥有它。在这种情况下,您应该将其作为共享指针存储在类中,并将其作为共享指针返回。在这种情况下,您可能会:
std::shared_ptr<DerivedInterface> m_xmlInterface;
std::unique_ptr<DerivedInterface> m_xmlInterface;
以及:
std::unique_ptr getBaseInterface()
{
返回std::move(m_xmlInterface);
}
不管有多大,注意:在任何人调用此函数后,您的类都不能再使用m_xmlInterface
,它失去了对它的所有所有权啊,对不起,我更新页面太快了,没有看到代码。从这个错误看来,
ReaderInterface
实际上并没有从IConfigurationInterface
继承,或者它是私下继承的(您没有:public IConfigurationInterface
)。我给出的代码示例是用g++8.2.0编译的。是的,这正是我想要实现的。你对代码应该是什么样子有什么建议吗?+1@Wballer3这里您可以在不同的编译器之间进行选择:@sgvd我有5.4.0Ah,对不起,我更新页面太快了,没有看到代码。从这个错误看来,ReaderInterface
实际上并没有从IConfigurationInterface
继承,或者它是私下继承的(您没有:public IConfigurationInterface
). 我给出的代码示例是用g++8.2.0编译的。是的,这正是我想要实现的。你对代码应该是什么样子有什么建议吗?+1@Wballer3这里您可以在不同的编译器之间进行选择:@sgvd I have 5.4.0
#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();
}
std::unique_ptr<DerivedInterface> m_xmlInterface;
std::unique_ptr<IBaseInterface> getBaseInterface()
{
return std::move(m_xmlInterface);
}