function template
<memory>

std::allocate_shared

template <class T, class Alloc, class... Args>
  shared_ptr<T> allocate_shared (const Alloc& alloc, Args&&... args);
Allocate shared_ptr
Allocates memory for an object of type T using alloc and constructs it passing args to its constructor. The function returns an object of type shared_ptr<T> that owns and stores a pointer to the constructed object (with a use count of 1).

This function uses alloc to allocate storage for the object. A similar function, make_shared uses ::new to allocate the storage instead.

Parameters

alloc
An allocator object.
Alloc is a type for which allocator_traits is well defined.
args
List of elements passed to T's constructor.
Args is a list of zero or more types.

Return Value

A shared_ptr object that owns and stores a pointer to a newly allocated object of type T.

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// allocate_shared example
#include <iostream>
#include <memory>

int main () {
  std::allocator<int> alloc;    // the default allocator for int
  std::default_delete<int> del; // the default deleter for int

  std::shared_ptr<int> foo = std::allocate_shared<int> (alloc,10);

  auto bar = std::allocate_shared<int> (alloc,20);

  auto baz = std::allocate_shared<std::pair<int,int>> (alloc,30,40);

  std::cout << "*foo: " << *foo << '\n';
  std::cout << "*bar: " << *bar << '\n';
  std::cout << "*baz: " << baz->first << ' ' << baz->second << '\n';

  return 0;
}


Output:
*foo: 10
*bar: 20
*baz: 30 40

See also