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.

[edit] Notes

This function allocates memory for the T object and for the shared_ptr's control block with a single memory allocation. In contrast, the declaration std::shared_ptr<T> p(new T(Args...)) performs two memory allocations, which may incur unnecessary overhead.

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