重新设置shared_ptr<派生>;来自接受shared_ptr的函数 派生>
我正在尝试从接受基类的 shared_ptr
的函数重新设置派生类的 shared_ptr
。
这个答案是相关的,但它没有涵盖我需要重新安装指针以便不能使用常量引用的事实。
这是一个 MWE:
#include <memory>
class A {
};
class B : public A {
};
class C {
public:
void doSomethingWithA(std::shared_ptr<A>& a){
a = std::make_shared<B>();
}
};
int main()
{
std::shared_ptr<B> b;
C c;
c.doSomethingWithA(b);
}
它给出了以下编译错误:
In function 'int main()':
21:23: error: no matching function for call to 'C::doSomethingWithA(std::shared_ptr<B>&)'
21:23: note: candidate is:
11:7: note: void C::doSomethingWithA(std::shared_ptr<A>&)
11:7: note: no known conversion for argument 1 from 'std::shared_ptr<B>' to 'std::shared_ptr<A>&'
代码背后的原因是可能有许多派生类,而我只在运行时知道要实例化哪一个。类C
将根据运行时发生的情况决定分配多种派生类型之一。
我不想创建 doSomethingWithA()
的多个重载,一般来说,将派生类的 shared_ptr
分配给 shared_ptr
是合法的> 基类的,所以我不明白为什么不能进行转换。
I'm trying to reseat a shared_ptr
of a derived class from a function that accept a shared_ptr
of a base class.
This answer is relevant, but it does not cover the fact that I need to reseat the pointer so a const reference cannot be used.
Here is a MWE:
#include <memory>
class A {
};
class B : public A {
};
class C {
public:
void doSomethingWithA(std::shared_ptr<A>& a){
a = std::make_shared<B>();
}
};
int main()
{
std::shared_ptr<B> b;
C c;
c.doSomethingWithA(b);
}
which gives the following compilation error:
In function 'int main()':
21:23: error: no matching function for call to 'C::doSomethingWithA(std::shared_ptr<B>&)'
21:23: note: candidate is:
11:7: note: void C::doSomethingWithA(std::shared_ptr<A>&)
11:7: note: no known conversion for argument 1 from 'std::shared_ptr<B>' to 'std::shared_ptr<A>&'
The reasoning behind the code is that there might be many derived classes and I know only at runtime which one is to be instantiated. The class C
would decide to assign one of many derived types depending on what happens at runtime.
I didn't want to create several overloads of doSomethingWithA()
and in general it is legal to assign a shared_ptr
of a derived class to a shared_ptr
of a base class, so I don't understand why the conversion is not possible.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用
std::static_pointer_cast
在这些类型之间进行转换,例如如果您需要的话,还有一个
std::dynamic_pointer_cast
但在本例中是static
会起作用的。You can convert between these types with
std::static_pointer_cast
e.g.There's also an
std::dynamic_pointer_cast
if you ever need that but in this casestatic
will work.