function template
<memory>

std::allocate_shared

template <class T, class Alloc, class... Args>  shared_ptr<T> allocate_shared (const Alloc& alloc, Args&&... args);
分配 shared_ptr
為型別物件分配記憶體T使用 alloc 並透過將 args 傳遞給其建構函式來構造它。該函式返回一個型別為shared_ptr<T>的物件,該物件擁有並存儲指向已構造物件的指標(其 use count1).

此函式使用 alloc 來分配物件的儲存。一個類似的函式,make_shared 使用::new來分配儲存。

引數

alloc
一個分配器物件。
Allocallocator_traits 定義良好的型別。
args
傳遞給T's 建構函式。
Args的元素列表。是一個或多個型別的列表。

返回值

一個 shared_ptr 物件,它擁有並存儲指向新分配的型別物件的指標T.

示例

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;
}

輸出
*foo: 10
*bar: 20
*baz: 30 40


另見