Boost :: Smart_ptrの使用方法多型で?
-
16-10-2019 - |
質問
スマートポインターをブーストします 多型で使用できます, 、しかし、どのようにしてサブクラスをポインターに戻しますか?
using namespace boost;
// ...
shared_ptr<SuperClass> a_ptr(new SubClass);
// ...
shared_ptr<SubClass> b_ptr = (shared_ptr<SubClass>)a_ptr; // Doesn't compile
最後の行はコンパイルされず、与えません error C2440: 'type cast' : cannot convert from 'boost::shared_ptr
<T>
' to 'boost::shared_ptr<T>
'
解決
使用する必要があります static_pointer_cast
:
struct B { virtual ~B() { } };
struct D : B { };
shared_ptr<B> bp(new D);
shared_ptr<D> dp(static_pointer_cast<D>(b));
(もあります dynamic_pointer_cast
と const_pointer_cast
それぞれ動的キャストとconstキャストを実行するため。)
所属していません StackOverflow