Cpp-standard-library-cpp-allocate-shared

提供:Dev Guides
移動先:案内検索

C ++メモリライブラリ-allocate_shared

説明

allocを使用してT型のオブジェクトにメモリを割り当て、コンストラクタに引数を渡して構築します。 この関数は、作成されたオブジェクトへのポインターを所有して保存するタイプshared_ptrのオブジェクトを返します。

宣言

以下は、std
allocate_sharedの宣言です。
template <class T, class Alloc, class... Args>
  shared_ptr<T> allocate_shared (const Alloc& alloc, Args&&... args);

C 11

template <class T, class Alloc, class... Args>
  shared_ptr<T> allocate_shared (const Alloc& alloc, Args&&... args);

パラメーター

  • args -アロケーターオブジェクトです。
  • alloc -0個以上のタイプのリストです。

戻り値

shared_ptrオブジェクトを返します。

例外

*noexcep* -例外をスローしません。

以下の例では、std
allocate_sharedについて説明しています。
#include <iostream>
#include <memory>

int main () {
   std::allocator<int> alloc;
   std::default_delete<int> del;

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

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

   auto baz = std::allocate_shared<std::pair<int,int>> (alloc,300,400);

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

   return 0;
}

上記のプログラムをコンパイルして実行すると、次の結果が生成されます-

*foo: 100
*bar: 200
*baz: 300 400