Come usare boost :: smart_ptr in polimorfismo?
-
16-10-2019 - |
Domanda
Boost puntatori intelligenti può essere utilizzato con il polimorfismo , ma come fai lanci retro sottoclasse al puntatore?
using namespace boost;
// ...
shared_ptr<SuperClass> a_ptr(new SubClass);
// ...
shared_ptr<SubClass> b_ptr = (shared_ptr<SubClass>)a_ptr; // Doesn't compile
L'ultima riga non lo fa di compilazione e dà error C2440: 'type cast' : cannot convert from 'boost::shared_ptr
<T>
' to 'boost::shared_ptr<T>
'
Soluzione
È necessario utilizzare 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));
(Ci sono anche dynamic_pointer_cast
e const_pointer_cast
per l'esecuzione di, rispettivamente, dinamica e calchi const.)
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow