##### cppreference.com

##### Search

Create account

##### Namespaces

- Page
- Discussion

##### Variants

##### Views

- View
- Edit
- History

##### Actions

# std::make_shared

From cppreference.com
< cpp‎ | memory‎ | shared ptr

Defined in header `<memory>` |  |
template< class T, class... Args > shared_ptr<T> make_shared( Args&&... args ); |  |

Constructs an object of type `T` and wraps it in a std::shared_ptr using `args` as the parameter list for the constructor of `T`.

### [edit] Parameters

args | - | list of arguments with which an instance of `T` will be constructed.

### [edit] Return value

std::shared_ptr of an instance of type `T`.

### [edit] Exceptions

May throw std::bad_alloc or any exception thrown by the constructor of `T`. If an exception is thrown, this function has no effect.

### [edit] Notes

This function typically allocates memory for the T object and for the shared_ptr's control block with a single memory allocation (it is a non-binding requirement in the Standard). In contrast, the declaration `std::shared_ptr<T> p(new T(Args...))` performs at least two memory allocations, which may incur unnecessary overhead.

Moreover, `f(shared_ptr<int>(new int(42)), g())` can lead to memory leak if `g` throws an exception. This problem doesn't exist if `make_shared` is used.

### [edit] Example

Run this code

    #include <iostream>
    #include <memory>

    void foo(std::shared_ptr<int> i)
    {
        (*i)++;
    }

    int main()
    {
        auto sp = std::make_shared<int>(10);
        foo(sp);
        std::cout << *sp << std::endl;
    }

Output:

    11

### [edit] See also

(constructor) | constructs new `shared_ptr` (public member function) [edit]
allocate_shared | creates a shared pointer that manages a new object allocated using an allocator (function template) [edit]

Retrieved from "http://en.cppreference.com/mwiki/index.php?title=cpp/memory/shared_ptr/make_shared&oldid=66566"