Namespaces
Variants

std:: make_unique, std:: make_unique_for_overwrite

From cppreference.net
Memory management library
( exposition only* )
Allocators
Uninitialized memory algorithms
Constrained uninitialized memory algorithms
Memory resources
Uninitialized storage (until C++20)
( until C++20* )
( until C++20* )
( until C++20* )

Garbage collector support (until C++23)
(C++11) (until C++23)
(C++11) (until C++23)
(C++11) (until C++23)
(C++11) (until C++23)
(C++11) (until C++23)
(C++11) (until C++23)
Definiert im Header <memory>
(1)
template < class T, class ... Args >
unique_ptr < T > make_unique ( Args && ... args ) ;
(seit C++14)
(bis C++23)
(nur für Nicht-Array-Typen)
template < class T, class ... Args >
constexpr unique_ptr < T > make_unique ( Args && ... args ) ;
(seit C++23)
(nur für Nicht-Array-Typen)
(2)
template < class T >
unique_ptr < T > make_unique ( std:: size_t size ) ;
(seit C++14)
(bis C++23)
(nur für Array-Typen mit unbekannter Grenze)
template < class T >
constexpr unique_ptr < T > make_unique ( std:: size_t size ) ;
(seit C++23)
(nur für Array-Typen mit unbekannter Grenze)
template < class T, class ... Args >
/* nicht spezifiziert */ make_unique ( Args && ... args ) = delete ;
(3) (seit C++14)
(nur für Array-Typen mit bekannter Grenze)
(4)
template < class T >
unique_ptr < T > make_unique_for_overwrite ( ) ;
(seit C++20)
(bis C++23)
(nur für Nicht-Array-Typen)
template < class T >
constexpr unique_ptr < T > make_unique_for_overwrite ( ) ;
(seit C++23)
(nur für Nicht-Array-Typen)
(5)
template < class T >
unique_ptr < T > make_unique_for_overwrite ( std:: size_t size ) ;
(seit C++20)
(bis C++23)
(nur für Array-Typen mit unbekannter Grenze)
template < class T >
constexpr unique_ptr < T > make_unique_for_overwrite ( std:: size_t size ) ;
(seit C++23)
(nur für Array-Typen mit unbekannter Grenze)
template < class T, class ... Args >
/* nicht spezifiziert */ make_unique_for_overwrite ( Args && ... args ) = delete ;
(6) (seit C++20)
(nur für Array-Typen mit bekannter Grenze)

Konstruiert ein Objekt vom Typ T und verpackt es in einen std::unique_ptr .

1) Konstruiert einen Nicht-Array-Typ T . Die Argumente args werden an den Konstruktor von T übergeben. Diese Überladung nimmt nur dann an der Überladungsauflösung teil, wenn T kein Array-Typ ist. Die Funktion ist äquivalent zu:
unique_ptr<T>(new T(std::forward<Args>(args)...))
2) Konstruiert ein Array der angegebenen dynamischen Größe. Die Array-Elemente werden wertinitialisiert . Diese Überladung nimmt nur dann an der Überladungsauflösung teil, wenn T ein Array mit unbekannter Grenze ist. Die Funktion ist äquivalent zu:
unique_ptr<T>(new std::remove_extent_t<T>[size]())
3,6) Die Konstruktion von Arrays mit bekannter Grenze ist nicht zulässig.
4) Gleich wie (1) , außer dass das Objekt default-initialized wird. Diese Überladung nimmt nur an der Überladaulösung teil, wenn T kein Array-Typ ist. Die Funktion ist äquivalent zu:
unique_ptr<T>(new T)
5) Gleich wie (2) , außer dass das Array default-initialized wird. Diese Überladung nimmt nur an der Überladungsauflösung teil, wenn T ein Array unbekannter Grenze ist. Die Funktion ist äquivalent zu:
unique_ptr<T>(new std::remove_extent_t<T>[size])

Inhaltsverzeichnis

Parameter

args - Liste der Argumente, mit denen eine Instanz von T konstruiert wird
size - die Länge des zu konstruierenden Arrays

Rückgabewert

std::unique_ptr einer Instanz vom Typ T .

Exceptions

Kann std::bad_alloc oder jede Ausnahme werfen, die vom Konstruktor von T geworfen wird. Falls eine Ausnahme geworfen wird, hat diese Funktion keine Wirkung.

Mögliche Implementierung

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;

Hinweise

Im Gegensatz zu std::make_shared (welches über std::allocate_shared verfügt), besitzt std::make_unique keine Allokator-bewusste Entsprechung. allocate_unique vorgeschlagen in P0211 müsste den Deleter-Typ D für den std:: unique_ptr < T,D > erfinden, den es zurückgibt, welcher ein Allokator-Objekt enthalten und sowohl destroy als auch deallocate in seinem operator ( ) aufrufen würde.

Feature-Test Makro Wert Std Funktion
__cpp_lib_make_unique 201304L (C++14) std::make_unique ; Überladung ( 1 )
__cpp_lib_smart_ptr_for_overwrite 202002L (C++20) Smart-Pointer-Erstellung mit Standardinitialisierung ( std::allocate_shared_for_overwrite , std::make_shared_for_overwrite , std::make_unique_for_overwrite ); Überladungen ( 4-6 )
__cpp_lib_constexpr_memory 202202L (C++23) constexpr für Überladungen ( 1,2,4,5 )

Beispiel

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

Ausgabe:

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]
**Übersetzte Elemente:** - "Run this code" → "Diesen Code ausführen" - "Output:" → "Ausgabe:" **Nicht übersetzte Elemente:** - Alle HTML-Tags und Attribute - Code innerhalb der `
` und `` Tags (C++ Code)
- C++-spezifische Begriffe und Schlüsselwörter
- Technische Kommentare im Code
- Ausgabe-Text (da dieser Teil der Code-Ausgabe ist)

Siehe auch

Konstruiert einen neuen unique_ptr
(Öffentliche Elementfunktion)
Erzeugt einen Shared Pointer, der ein neues Objekt verwaltet
(Funktionstemplate)