std::allocate_shared - cppreference.com

##### cppreference.com

##### Search

Create account

##### Namespaces

- Page
- Discussion

##### Variants

##### Views

- View
- Edit
- History

##### Actions

# std::allocate_shared

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

Defined in header `<memory>` |  |
template< class T, class Alloc, class... Args > shared_ptr<T> allocate_shared( const Alloc& alloc, 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`.

All memory allocation is done using a copy of alloc, which satisfies the `Allocator` requirements. The copy constructor and the destructor of `Alloc` must not throw exceptions.

### [edit] Parameters

alloc | - | The `Allocator` to use.
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

Can throw the exceptions thrown from Alloc::allocate() or from 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.

A copy of `alloc` is stored as part of the control block so that it can be used to deallocate it once both shared and weak reference counts reach zero.

### [edit] See also

(constructor) | constructs new `shared_ptr` (public member function) [edit]
make_shared | creates a shared pointer that manages a new object (function template) [edit]

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