#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;
}
Run Code Online (Sandbox Code Playgroud)
错误:不能dynamic_cast`(&a) - > std :: auto_ptr <_Tp> :: get()const
Joh*_*itb 11
好吧,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);
Run Code Online (Sandbox Code Playgroud)
对于auto_ptr,这样的事情无法真正起作用.因为所有权将转移到b
.但如果演员表失败,b就无法获得所有权.目前还不清楚该怎么办.您可能不得不说,如果演员表失败,将继续拥有所有权 - 这听起来会导致严重的麻烦.最好开始使用shared_ptr.两者a
并b
随后将指向同一个对象-但B
作为shared_ptr<B>
和a
作为shared_ptr<A>
动态转换不起作用.A : public B
并不意味着auto_ptr<A> : public auto_ptr<B>
.这就是boost shared_ptr
提供的原因shared_dynamic_cast
.你可以写一个auto_ptr
动态演员:
template<typename R, typename T>
std::auto_ptr<R> auto_ptr_dynamic_cast(std::auto_ptr<T>& in) {
auto_ptr<R> rv;
R* p;
if( p = dynamic_cast<R*>( in.get() ) ) {
in.release();
rv = p;
}
return rv;
Run Code Online (Sandbox Code Playgroud)
}
请注意这里发生的事情.由于auto_ptr
s具有所有权语义,因此成功的向下转换意味着原始更通常的类型,auto_ptr不再拥有所有权.
归档时间: |
|
查看次数: |
2791 次 |
最近记录: |