Namespaces
Variants
Views
Actions

std::make_shared

From cppreference.com
< cpp‎ | memory‎ | shared ptr
Revision as of 23:13, 31 May 2013 by P12bot (Talk | contribs)

 
 
 
 
 
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

Parameters

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

Return value

std::shared_ptr of an instance of type T.

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.

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.

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

See also

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