首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

std::make_unique

Defined in header <memory>

?

?

template< class T, class... Args > unique_ptr<T> make_unique( Args&&... args );

(1)

(since C++14)(only for non-array types)

template< class T > unique_ptr<T> make_unique( std::size_t size );

(2)

(since C++14)(only for array types with unknown bound)

template< class T, class... Args > /* unspecified */ make_unique( Args&&... args ) = delete;

(3)

(since C++14)(only for array types with known bound)

构造类型的对象。T并将其包装在std::unique_ptr...

1%29构造非数组类型。T.论点args的构造函数传递给T。此重载只参与以下情况下的过载解决方案:T不是数组类型。该职能相当于:

二次

代码语言:javascript
复制
unique_ptr<T>(new T(std::forward<Args>(args)...))

二次

2%29构造一个未知界数组。T。此重载只参与以下情况下的过载解决方案:T是一个未知界限的数组。该职能相当于:

二次

代码语言:javascript
复制
unique_ptr<T>(new typename std::remove_extent<T>::type[size]())

二次

3%29已知界数组的构造是不允许的。

参数

args

-

list of arguments with which an instance of T will be constructed.

size

-

the size of the array to construct

返回值

std::unique_ptr类型实例的T...

例外

可抛std::bad_alloc的构造函数引发的任何异常。T如果抛出异常,则此函数没有任何效果。

可能的实施

//注意:此实现不禁用数组类型模板<type Name T,type Name...。ARGS>STD::UNIQUE[医]PTR<T>制造[医]唯一%28 Args&...args%29{返回STD::UNIQUE[医]PTR<T>%28新T%28 std::正向<Args>%28 args%29...%29%29;}

*。

注记

不像std::make_shared%28std::allocate_shared%29,std::make_unique没有分配器感知的对应。假想allocate_unique将需要发明删除类型。Dunique_ptr<T,D>它返回包含一个分配器对象并同时调用这两个对象的destroydeallocate在其operator()...

二次

代码语言:javascript
复制
#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()
{
    // Use the default constructor.
    std::unique_ptr<Vec3> v1 = std::make_unique<Vec3>();
    // Use the constructor that matches these arguments
    std::unique_ptr<Vec3> v2 = std::make_unique<Vec3>(0, 1, 2);
    // Create a unique_ptr to an array of 5 elements
    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';
    }
}

二次

产出:

二次

代码语言:javascript
复制
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}

二次

另见

(constructor)

constructs a new unique_ptr (public member function)

make_shared

creates a shared pointer that manages a new object (function template)

代码语言:txt
复制
 ? cppreference.com

在CreativeCommonsAttribution下授权-ShareAlike未移植许可v3.0。

扫码关注腾讯云开发者

领取腾讯云代金券

http://www.vxiaotou.com