I want to use the make_shared<T>
function with a derived class, like below
class Base { public: typedef std::shared_ptr<Base> Ptr; }; class Derived : public Base {}; Base::Ptr myPtr = std::make_shared(/* Derived() */ );
How can I tell make_shared to build such an object?
I want to avoid the classical
Base::Ptr ptr = Base::Ptr(new Derived());
To make use of the single alloc in the make_shared function.
std::make_sharedAllocates and constructs an object of type T passing args to its constructor, and returns an object of type shared_ptr<T> that owns and stores a pointer to it (with a use count of 1). This function uses ::new to allocate storage for the object.
The statement that uses make_shared is simpler because there's only one function call involved. It's more efficient because the library can make a single allocation for both the object and the smart pointer.
So, if you throw exception from your class' constructor, then std::make_shared will throw it too. Besides exceptions thrown from constructor, std::make_shared could throw std::bad_alloc exception on its own.
std::shared_ptr
has a converting constructor that can make a shared_ptr<Base>
from a shared_ptr<Derived>
, so the following should work:
#include <memory> class Base { public: typedef std::shared_ptr<Base> Ptr; }; class Derived : public Base {}; int main() { Base::Ptr myPtr = std::make_shared<Derived>(); }
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