Search code examples
c++unique-ptr

How do you make unique_ptrs with the these initializations?


What are the equivalent versions of making std::unique_ptr using std::make_unique with the following initializations?

// Single object
// 1: Indeterminate value
new int; 
// 2: Zero initialized
new int();
// 3: Initialized with 7
new int(7);

    
// Arrays
// 1: Indeterminate values
new int[10];
// 2: All zero-initialized
new int[10]();
// 3: Initialized with list, (rest all zero)
new int[10]{ 7, 6, 5, 4 };

Solution

  • The counter parts are:

    // Single object
    // 1: Indeterminate value
    new int;
    std::make_unique_for_overwrite<int>(); // since C++20
    
    // 2: Zero initialized
    new int();
    std::make_unique<int>();
    
    // 3: Initialized with 7
    new int(7);
    std::make_unique<int>(7);
    
    // Arrays
    // 1: Indeterminate values
    new int[10];
    std::make_unique_for_overwrite<int[]>(10); // Since C++20
    // 2: All zero-initialized
    new int[10]();
    std::make_unique<int[]>(10);
    // 3: Initialized with list, (rest all zero).
    new int[10]{ 7, 6, 5, 4 };
    std::unique_ptr<int[]>{ new int[10]{ 7, 6, 5, 4 } };
    

    std::make_unique_for_overwrite is C++20 only.