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不是数组类型。该职能相当于:
二次
unique_ptr<T>(new T(std::forward<Args>(args)...))二次
2%29构造一个未知界数组。T。此重载只参与以下情况下的过载解决方案:T是一个未知界限的数组。该职能相当于:
二次
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将需要发明删除类型。D为unique_ptr<T,D>它返回包含一个分配器对象并同时调用这两个对象的destroy和deallocate在其operator()...
例
二次
#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';
}
}二次
产出:
二次
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) |
© cppreference.com在CreativeCommonsAttribution下授权-ShareAlike未移植许可v3.0。
本文档系腾讯云开发者社区成员共同维护,如有问题请联系 cloudcommunity@tencent.com

