共用方式為


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();
}

當您看到錯誤 C2280 與 unique_ptr 有關時,通常都是因為您嘗試叫用一個已被刪除的複製建構函式。

需求

<記憶體>

請參閱

工作

如何:建立和使用 unique_ptr 執行個體