Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make_shared a derived class?

Tags:

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.

like image 876
Sam Avatar asked Jul 26 '14 06:07

Sam


People also ask

What is Make_shared in C++?

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.

Why is Make_shared more efficient?

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.

Does Make_shared throw?

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.


1 Answers

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>(); } 
like image 79
Mankarse Avatar answered Sep 17 '22 10:09

Mankarse