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?
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.
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.
std::shared_ptr is a smart pointer that retains shared ownership of an object through a pointer.
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.
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);
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