Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

static_cast with boost::shared_ptr?

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 = ??? 
like image 306
Frank Avatar asked Mar 09 '09 02:03

Frank


People also ask

What is boost :: shared_ptr?

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.

Can you cast a shared pointer?

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).

How is static_cast implemented?

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.


1 Answers

Use boost::static_pointer_cast:

boost::shared_ptr<Base> b(new Derived()); boost::shared_ptr<Derived> d = boost::static_pointer_cast<Derived>(b); 
like image 127
Frank Avatar answered Sep 17 '22 13:09

Frank