Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dynamic_cast across a shared_ptr?

I have two classes A and B, B inherits from A.

If I have a shared_ptr<A> object which I know is really a B subtype, how can I perform a dynamic cast to access the API of B (bearing in mind my object is shared_ptr, not just A?

like image 363
mezamorphic Avatar asked May 21 '14 23:05

mezamorphic


People also ask

What happens when shared_ptr goes out of scope?

The smart pointer has an internal counter which is decreased each time that a std::shared_ptr , pointing to the same resource, goes out of scope – this technique is called reference counting. When the last shared pointer is destroyed, the counter goes to zero, and the memory is deallocated.

Can you return a shared_ptr?

So the best way to return a shared_ptr is to simply return by value: shared_ptr<T> Foo() { return shared_ptr<T>(/* acquire something */); }; This is a dead-obvious RVO opportunity for modern C++ compilers.

What is the purpose of the shared_ptr <> template?

std::shared_ptr is a smart pointer that retains shared ownership of an object through a pointer.

Is Static_cast faster than Dynamic_cast?

While typeid + static_cast is faster than dynamic_cast , not having to switch on the runtime type of the object is faster than any of them.


1 Answers

If you just want to call a function from B you can use one of these:

std::shared_ptr<A> ap = ...; dynamic_cast<B&>(*ap).b_function(); if (B* bp = dynamic_cast<B*>(ap.get()) {     ... } 

In case you actually want to get a std::shared_ptr<B> from the std::shared_ptr<A>, you can use use

std::shared_ptr<B> bp = std::dynamic_pointer_cast<B>(ap); 
like image 58
Dietmar Kühl Avatar answered Oct 04 '22 12:10

Dietmar Kühl