make_unique

创建并返回 unique_ptr 至指定类型的对象,该对象是使用指定的参数构造的。

// make_unique<T>
template<class T, 
    class... Types>
    unique_ptr<T> make_unique(Types&&... Args)
    {
    return (unique_ptr<T>(new T(forward<Types>(Args)...))); 
    }

// make_unique<T[]>
template<class T>
    make_unique(size_t Size) 
    { 
    return (unique_ptr<T>(new Elem[Size]())); 
    }

// make_unique<T[N]> disallowed
template<class T, 
    class... Types>
    typename enable_if<extent<T>::value != 0, 
        void>::type make_unique(Types&&...) = delete; 

参数

  • T
    独特的 unique_ptr 将指向的对象类型。

  • Types
    Args 指定的构造函数的类型。

  • Args
    要传递到 T 类型对象的构造函数的参数。

  • Elem
    一个由 T 元素组成的数组。

  • Size
    新数组中待分配空间的元素数。

返回值

指定类型 T 对象的 unique_ptr

备注

第一个重载用于单个对象,第二个重载为数组调用,第三个重载防止您指定类型参数的数组大小((make_unique<T[N]>);目前的标准不支持这种结构。 当使用 make_unique 创建 unique_ptr 到数组时,您必须单独初始化数组元素。 如果您正在考虑此重载,也许使用 std::vector 是更好的选择。

因为 make_unique 是精心为异常安全实现的,我们建议您使用make_unique而不是直接调用的unique_ptr构造函数。

示例

下面的示例显示如何使用 make_unique。 有关更多示例,请参见如何:创建和使用 unique_ptr 实例

class Animal
{
private:
    std::wstring genus;
    std::wstring species;
    int age;
    double weight;
public:
    Animal(const wstring&, const wstring&, int, double){/*...*/ }
    Animal(){}
};

void MakeAnimals()
{
    // Use the Animal default constructor.
    unique_ptr<Animal> p1 = make_unique<Animal>();

    // Use the constructor that matches these arguments
    auto p2 = make_unique<Animal>(L"Felis", L"Catus", 12, 16.5);

    // Create a unique_ptr to an array of 5 Animals
    unique_ptr<Animal[]> p3 = make_unique<Animal[]>(5);

    // Initialize the elements
    p3[0] = Animal(L"Rattus", L"norvegicus", 3, 2.1);
    p3[1] = Animal(L"Corynorhinus", L"townsendii", 4, 1.08);

    // auto p4 = p2; //C2280

    vector<unique_ptr<Animal>> vec;
    // vec.push_back(p2); //C2280 
    // vector<unique_ptr<Animal>> vec2 = vec; // C2280 

    // OK. p2 no longer points to anything
    vec.push_back(std::move(p2)); 

    // unique_ptr overloads operator bool
    wcout << boolalpha << (p2 == false) << endl; // Prints "true" 

    // OK but now you have two pointers to the same memory location
    Animal* pAnimal = p2.get();

    // OK. p2 no longer points to anything
    Animal* p5 = p2.release();
}

当你看到带unique_ptr的连接错误C2280,几乎可以肯定,因为你正试图调用它的拷贝构造函数,这是一个已删除的功能。

要求

<内存>

请参见

任务

如何:创建和使用 unique_ptr 实例