std::make_unique

定义于头文件 <memory>
template< class T, class... Args >
unique_ptr<T> make_unique( Args&&... args );
(1) (C++14 起)
(仅对非数组类型)
template< class T >
unique_ptr<T> make_unique( std::size_t size );
(2) (C++14 起)
(仅对未知边界数组)
template< class T, class... Args >
/* unspecified */ make_unique( Args&&... args ) = delete;
(3) (C++14 起)
(仅对已知边界数组)

构造 T 类型对象并将其包装进 std::unique_ptr

1) 构造一个非数组类型 T 。传递参数 argsT 的构造函数。此重载仅若 T 不是数组类型才参与重载决议。函数等价于:
unique_ptr<T>(new T(std::forward<Args>(args)...))
2) 构造未知边界的 T 数组。此重载仅若 T 是未知边界数组才参与重载决议。函数等价于:
unique_ptr<T>(new typename std::remove_extent<T>::type[size]())
3) 不允许构造已知边界的数组。

目录

参数

args - 将要构造的 T 实例所用的参数列表。
size - 要构造的数组大小

返回值

类型 T 实例的 std::unique_ptr

异常

可能抛出 std::bad_alloc 或任何 T 的构造函数所抛的异常。若抛出异常,则此函数无效果。

可能的实现

// 注意:此实现不为数组类型禁用此重载
template<typename T, typename... Args>
std::unique_ptr<T> make_unique(Args&&... args)
{
    return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
}

注意

不同于 std::make_shared (它拥有 std::allocate_shared ), std::make_unique 没有具分配器的对应物。假设的 allocate_unique 会要求为其返回的 unique_ptr<T,D> 创作删除器类型 D ,返回类型可能含有分配器对象,并在其 operator() 调用 destroydeallocate

示例

#include <iostream>
#include <memory>
 
struct Vec3
{
    int x, y, z;
    Vec3() : x(0), y(0), z(0) { }
    Vec3(int x, int y, int z) :x(x), y(y), z(z) { }
    friend std::ostream& operator<<(std::ostream& os, Vec3& v) {
        return os << '{' << "x:" << v.x << " y:" << v.y << " z:" << v.z  << '}';
    }
};
 
int main()
{
    // 使用默认构造函数。
    std::unique_ptr<Vec3> v1 = std::make_unique<Vec3>();
    // 使用匹配这些参数的构造函数
    std::unique_ptr<Vec3> v2 = std::make_unique<Vec3>(0, 1, 2);
    // 创建指向 5 个元素数组的 unique_ptr 
    std::unique_ptr<Vec3[]> v3 = std::make_unique<Vec3[]>(5);
 
    std::cout << "make_unique<Vec3>():      " << *v1 << '\n'
              << "make_unique<Vec3>(0,1,2): " << *v2 << '\n'
              << "make_unique<Vec3[]>(5):   " << '\n';
    for (int i = 0; i < 5; i++) {
        std::cout << "     " << v3[i] << '\n';
    }
}

输出:

make_unique<Vec3>():      {x:0 y:0 z:0}
make_unique<Vec3>(0,1,2): {x:0 y:1 z:2}
make_unique<Vec3[]>(5):   
     {x:0 y:0 z:0}
     {x:0 y:0 z:0}
     {x:0 y:0 z:0}
     {x:0 y:0 z:0}
     {x:0 y:0 z:0}

参阅

构造新的unique_ptr
(公开成员函数)
创建管理新对象的共享指针
(函数模板)

版本历史

  • (当前 | 先前 2017年9月8日 (五) 10:58Fruderica讨论 | 贡献 . . (3,474字节) (-3). . (撤销)
  • 当前 | 先前) 2017年5月4日 (四) 06:58Fruderica讨论 | 贡献. . (3,477字节) (+3,477). . (以“{{cpp/title|make_unique}} {{cpp/memory/unique_ptr/navbar}} {{dcl begin}} {{dcl header | memory}} {{dcl | num=1 | notes={{mark since c++14}}<br/>{{mark|仅对非数...”为内容创建页面)