std::make_shared

From cppreference.com
 
 
 
 
 
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.

Contents

[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 contructor 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

#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

constructs new shared_ptr
(public member function)
creates a shared pointer that manages a new object allocated using an allocator
(function template)