What is the equivalent of a static_cast
with boost::shared_ptr
?
In other words, how do I have to rewrite the following
Base* b = new Derived(); Derived* d = static_cast<Derived*>(b);
when using shared_ptr
?
boost::shared_ptr<Base> b(new Derived()); boost::shared_ptr<Derived> d = ???
shared_ptr is now part of the C++11 Standard, as std::shared_ptr . Starting with Boost release 1.53, shared_ptr can be used to hold a pointer to a dynamically allocated array. This is accomplished by using an array type ( T[] or T[N] ) as the template parameter.
Casting shared pointers in C++We can either cast the shared pointer directly by setting the type to the DerivedClass, or just use the raw points with “. get()” and static_cast in the second approach (direct cast).
static_cast is always resolved using compile-time type info. (This may involve a runtime action). If it's not an appropriate cast you either get a compile error or undefined behaviour. In your snippet it is OK because b is a D ; however if b were new B() then the cast compiles but causes undefined behaviour if run.
Use boost::static_pointer_cast
:
boost::shared_ptr<Base> b(new Derived()); boost::shared_ptr<Derived> d = boost::static_pointer_cast<Derived>(b);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With