目录

allocate_shared

描述 (Description)

它使用alloc为类型为T的对象分配内存,并构造它将args传递给它的构造函数。 该函数返回shared_ptr类型的对象 拥有并存储指向构造对象的指针。

声明 (Declaration)

以下是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);

参数 (Parameters)

  • args - 它是一个分配器对象。

  • alloc - 它是零个或多个类型的列表。

返回值 (Return Value)

它返回一个shared_ptr对象。

异常 (Exceptions)

noexcep - 它不会抛出任何异常。

例子 (Example)

在下面的例子中解释了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
↑回到顶部↑
WIKI教程 @2018