名稱空間
變體
操作

std::make_unique, std::make_unique_for_overwrite

來自 cppreference.com
< cpp‎ | memory‎ | unique ptr
 
 
記憶體管理庫
(僅作說明*)
未初始化記憶體演算法
(C++17)
(C++17)
(C++17)
受約束的未初始化
記憶體演算法
C 庫

分配器
記憶體資源
垃圾回收支援
(C++11)(直到 C++23)
(C++11)(直到 C++23)
(C++11)(直到 C++23)
(C++11)(直到 C++23)
(C++11)(直到 C++23)
(C++11)(直到 C++23)
未初始化儲存
(直到 C++20*)
(直到 C++20*)
顯式生命週期管理
 
 
定義於標頭檔案 <memory>
(1)
template< class T, class... Args >
unique_ptr<T> make_unique( Args&&... args );
(C++14 起)
(直至 C++23)
(僅用於非陣列型別)
template< class T, class... Args >
constexpr unique_ptr<T> make_unique( Args&&... args );
(C++23 起)
(僅用於非陣列型別)
(2)
template< class T >
unique_ptr<T> make_unique( std::size_t size );
(C++14 起)
(直至 C++23)
(僅用於未知邊界的陣列型別)
template< class T >
constexpr unique_ptr<T> make_unique( std::size_t size );
(C++23 起)
(僅用於未知邊界的陣列型別)
template< class T, class... Args >
/* 未指定 */ make_unique( Args&&... args ) = delete;
(3) (C++14 起)
(僅用於已知邊界的陣列型別)
(4)
template< class T >
unique_ptr<T> make_unique_for_overwrite();
(C++20 起)
(直至 C++23)
(僅用於非陣列型別)
template< class T >
constexpr unique_ptr<T> make_unique_for_overwrite();
(C++23 起)
(僅用於非陣列型別)
(5)
template< class T >
unique_ptr<T> make_unique_for_overwrite( std::size_t size );
(C++20 起)
(直至 C++23)
(僅用於未知邊界的陣列型別)
template< class T >
constexpr unique_ptr<T> make_unique_for_overwrite( std::size_t size );
(C++23 起)
(僅用於未知邊界的陣列型別)
template< class T, class... Args >
/* 未指定 */ make_unique_for_overwrite( Args&&... args ) = delete;
(6) (C++20 起)
(僅用於已知邊界的陣列型別)

構造一個型別為 T 的物件並將其封裝在 std::unique_ptr 中。

1) 構造一個非陣列型別 T。引數 args 被傳遞給 T 的建構函式。此過載僅在 T 不是陣列型別時參與過載決議。該函式等價於
unique_ptr<T>(new T(std::forward<Args>(args)...))
2) 構造給定動態大小的陣列。陣列元素是值初始化的。此過載僅在 T 是未知邊界的陣列時參與過載決議。該函式等價於
unique_ptr<T>(new std::remove_extent_t<T>[size]())
3,6) 禁止構造已知邊界的陣列。
4)(1) 相同,但物件是預設初始化的。此過載僅在 T 不是陣列型別時參與過載決議。該函式等價於
unique_ptr<T>(new T)
5)(2) 相同,但陣列是預設初始化的。此過載僅在 T 是未知邊界的陣列時參與過載決議。該函式等價於
unique_ptr<T>(new std::remove_extent_t<T>[size])

目錄

[編輯] 引數

args - 用於構造 T 例項的引數列表
size - 要構造的陣列的長度

[編輯] 返回值

型別為 T 的例項的 std::unique_ptr

[編輯] 異常

可能丟擲 std::bad_allocT 的建構函式丟擲的任何異常。如果丟擲異常,此函式無效。

[編輯] 可能的實現

make_unique (1-3)
// C++14 make_unique
namespace detail
{
    template<class>
    constexpr bool is_unbounded_array_v = false;
    template<class T>
    constexpr bool is_unbounded_array_v<T[]> = true;
 
    template<class>
    constexpr bool is_bounded_array_v = false;
    template<class T, std::size_t N>
    constexpr bool is_bounded_array_v<T[N]> = true;
} // namespace detail
 
template<class T, class... Args>
std::enable_if_t<!std::is_array<T>::value, std::unique_ptr<T>>
make_unique(Args&&... args)
{
    return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
}
 
template<class T>
std::enable_if_t<detail::is_unbounded_array_v<T>, std::unique_ptr<T>>
make_unique(std::size_t n)
{
    return std::unique_ptr<T>(new std::remove_extent_t<T>[n]());
}
 
template<class T, class... Args>
std::enable_if_t<detail::is_bounded_array_v<T>> make_unique(Args&&...) = delete;
make_unique_for_overwrite (4-6)
// C++20 make_unique_for_overwrite
template<class T>
    requires (!std::is_array_v<T>)
std::unique_ptr<T> make_unique_for_overwrite()
{
    return std::unique_ptr<T>(new T);
}
 
template<class T>
    requires std::is_unbounded_array_v<T>
std::unique_ptr<T> make_unique_for_overwrite(std::size_t n)
{
    return std::unique_ptr<T>(new std::remove_extent_t<T>[n]);
}
 
template<class T, class... Args>
    requires std::is_bounded_array_v<T>
void make_unique_for_overwrite(Args&&...) = delete;

[編輯] 注意

std::make_shared(它有 std::allocate_shared)不同,std::make_unique 沒有 allocator-aware 的對應項。P0211 中提議的 allocate_unique 將需要為它返回的 std::unique_ptr<T,D> 發明刪除器型別 D,該型別將包含一個分配器物件並在其 operator() 中呼叫 destroydeallocate

特性測試 標準 特性
__cpp_lib_make_unique 201304L (C++14) std::make_unique;過載 (1)
__cpp_lib_smart_ptr_for_overwrite 202002L (C++20) 使用預設初始化的智慧指標建立(std::allocate_shared_for_overwritestd::make_shared_for_overwritestd::make_unique_for_overwrite);過載 (4-6)
__cpp_lib_constexpr_memory 202202L (C++23) 過載 (1,2,4,5)constexpr

[編輯] 示例

#include <cstddef>
#include <iomanip>
#include <iostream>
#include <memory>
#include <utility>
 
struct Vec3
{
    int x, y, z;
 
    // Following constructor is no longer needed since C++20.
    Vec3(int x = 0, int y = 0, int z = 0) noexcept : x(x), y(y), z(z) {}
 
    friend std::ostream& operator<<(std::ostream& os, const Vec3& v)
    {
        return os << "{ x=" << v.x << ", y=" << v.y << ", z=" << v.z << " }";
    }
};
 
// Output Fibonacci numbers to an output iterator.
template<typename OutputIt>
OutputIt fibonacci(OutputIt first, OutputIt last)
{
    for (int a = 0, b = 1; first != last; ++first)
    {
        *first = b;
        b += std::exchange(a, b);
    }
    return first;
}
 
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);
 
    // Create a unique_ptr to an uninitialized array of 10 integers,
    // then populate it with Fibonacci numbers.
    std::unique_ptr<int[]> i1 = std::make_unique_for_overwrite<int[]>(10);
    fibonacci(i1.get(), i1.get() + 10);
 
    std::cout << "make_unique<Vec3>():      " << *v1 << '\n'
              << "make_unique<Vec3>(0,1,2): " << *v2 << '\n'
              << "make_unique<Vec3[]>(5):   ";
    for (std::size_t i = 0; i < 5; ++i)
        std::cout << std::setw(i ? 30 : 0) << v3[i] << '\n';
    std::cout << '\n';
 
    std::cout << "make_unique_for_overwrite<int[]>(10), fibonacci(...): [" << i1[0];
    for (std::size_t i = 1; i < 10; ++i)
        std::cout << ", " << i1[i];
    std::cout << "]\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 }
 
make_unique_for_overwrite<int[]>(10), fibonacci(...): [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]

[編輯] 另請參閱

構造一個新的 unique_ptr
(公共成員函式) [編輯]
建立一個管理新物件的共享指標
(函式模板) [編輯]