std::make_u...or_overwrite(3)

πŸ“¦ version 2024.07.05, in nixpkgs unstable, opensuse-leap 16.0

bestie, welcome to the std::make_u...or_overwrite(3) page from the C++ Standard Library manual. This is the group chat where we make smart pointers and absolutely do not raw-new in public. 🫢

πŸ’– NAME πŸ’–

std::make_unique, std::make_unique_for_overwrite β€” that's the whole name, no cap. These two are the factory besties for std::unique_ptr.

✨ Synopsis ✨

Defined in header <memory>

// (1) (since C++14) (until C++23) (only for non-array types)
template< class T, class... Args >
unique_ptr<T> make_unique( Args&&... args );

// (1) (since C++23) (only for non-array types)
template< class T, class... Args >
constexpr unique_ptr<T> make_unique( Args&&... args );

// (2) (since C++14) (until C++23) (only for array types with unknown bound)
template< class T >
unique_ptr<T> make_unique( std::size_t size );

// (2) (since C++23) (only for array types with unknown bound)
template< class T >
constexpr unique_ptr<T> make_unique( std::size_t size );

// (3) (since C++14) (only for array types with known bound)
template< class T, class... Args >
/* unspecified */ make_unique( Args&&... args ) = delete;

// (4) (since C++20) (until C++23) (only for non-array types)
template< class T >
unique_ptr<T> make_unique_for_overwrite();

// (4) (since C++23) (only for non-array types)
template< class T >
constexpr unique_ptr<T> make_unique_for_overwrite();

// (5) (since C++20) (until C++23) (only for array types with unknown bound)
template< class T >
unique_ptr<T> make_unique_for_overwrite( std::size_t size );

// (5) (since C++23) (only for array types with unknown bound)
template< class T >
constexpr unique_ptr<T> make_unique_for_overwrite( std::size_t size );

// (6) (since C++20) (only for array types with known bound)
template< class T, class... Args >
/* unspecified */ make_unique_for_overwrite( Args&&... args ) = delete;

Okay so the main character move: construct an object of type T and wrap it in a std::unique_ptr. The overloads break down like this:

  1. Constructs a non-array type T. The arguments args are passed to the constructor of T. This overload participates in overload resolution only if T is not an array type. The function is equivalent to:
unique_ptr<T>(new T(std::forward<Args>(args)...))
  1. Constructs an array of the given dynamic size. The array elements are value-initialized. This overload participates in overload resolution only if T is an array of unknown bound. The function is equivalent to:
unique_ptr<T>(new std::remove_extent_t<T>[size]())
  1. and 6) Construction of arrays of known bound is disallowed. 🚫
  2. Same as (1), except that the object is default-initialized. This overload participates in overload resolution only if T is not an array type. The function is equivalent to:
unique_ptr<T>(new T)
  1. Same as (2), except that the array is default-initialized. This overload participates in overload resolution only if T is an array of unknown bound. The function is equivalent to:
unique_ptr<T>(new std::remove_extent_t<T>[size])

πŸŽ€ Parameters πŸŽ€

  • args β€” list of arguments with which an instance of T will be constructed.
  • size β€” the length of the array to construct.

🌈 Return value 🌈

std::unique_ptr of an instance of type T. Periodt.

πŸ’€ Exceptions πŸ’€

May throw std::bad_alloc or any exception thrown by the constructor of T. If an exception is thrown, this function has no effect. That's the safety net, bestie β€” no half-built object left on read.

✨ EXAMPLE ✨

🫢 heads up bestie: this section is incomplete β€” reason given on the page is literally "add more make_unique_for_overwrite() demos". so like, it's a work in progress, don't come for me πŸ’…

okay so here's the whole runnable demo, copy-paste it into your editor and watch it slay:

// Run this code

#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";
}

and the moment you've all been waiting for, the output πŸ’–:

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]

like, the way make_unique<Vec3[]>(5) gives you five whole default-initialized Vec3s and then the for_overwrite version gives you ten uninitialized ints that you get to fill yourself β€” it's giving "blank canvas, you're the artist" 🎨✨ obsessed.


🌸 SEE ALSO 🌸

the friends of this function, the squad, the supporting cast 🫢:

  • constructor β€” constructs a new unique_ptr (public member function)
  • make_shared β€” creates a shared pointer that manages a new object
  • make_shared_for_overwrite β€” (function template) (C++20)

and for the completionists, the page's own little category tag at the bottom says:

  • Todo with reason 🫑

🌈 okay that's the whole page, bestie, you're officially fluent in make_unique_for_overwrite now. go forth and not zero-initialize your arrays. πŸ‘‘

πŸ› this gem came from cppreference.com, stamped 2024.06.10 β€” cite it with love, k? mwah πŸ’‹πŸŽ€

πŸ“¦ where this page comes from