#include "iostream"
class A {
private:
int a;
public :
A(): a(-1) {}
int getA() {
return a;
}
};
class A;
class B : public A {
private:
int b;
public:
B() : b(-1) {}
int getB() {
return b;
}
};
int main() {
std::auto_ptr<A> a = new A();
std::auto_ptr<B> b = dynamic_cast<std::auto_ptr<B> > (a);
return 0;
}
错误:不能 dynamic_cast `(&a)->std::auto_ptr<_Tp>::get() const
最佳答案
嗯,std::auto_ptr<B>
不是来自 std::auto_ptr<A>
.但是B
源自 A
. auto_ptr 不知道这一点(它不是那么聪明)。看起来您想使用共享所有权指针。 boost::shared_ptr
很理想,它还提供了一个dynamic_pointer_cast:
boost::shared_ptr<A> a = new A();
boost::shared_ptr<B> b = dynamic_pointer_cast<B> (a);
对于auto_ptr来说,这样的东西真的行不通。因为所有权将转移到 b
.但如果转换失败,b 就无法获得所有权。目前还不清楚该对我做什么。你可能不得不说,如果类型转换失败,a 将继续拥有所有权——这听起来会造成严重的麻烦。最好开始使用 shared_ptr。两者 a
和 b
然后会指向同一个对象——但是B
作为shared_ptr<B>
和 a
作为shared_ptr<A>
关于c++ - 为什么这个 auto_ptr 的 dynamic_cast 会失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/518959/