我正在尝试从接受基类的shared_ptr的函数中重新获取派生类的shared_ptr。
This answer是相关的,但它没有涵盖这样一个事实,即我需要重新设置指针,这样就不能使用const引用。
这是一个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是合法的,所以我不明白为什么不可能进行转换。
发布于 2022-03-14 16:03:48
您可以使用std::static_pointer_cast在这些类型之间进行转换。
#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;
std::shared_ptr<A> a_ptr_from_b = std::static_pointer_cast<A>(b);
c.doSomethingWithA(a_ptr_from_b);
}如果需要的话,还有一个std::dynamic_pointer_cast,但是在这种情况下,static会工作的。
https://stackoverflow.com/questions/71470652
复制相似问题