Namespaces
Variants
Views
Actions

Difference between revisions of "cpp/memory/unique ptr/make unique"

From cppreference.com
< cpp‎ | memory‎ | unique ptr
m (link to zh)
m (fmt, <cstddef> for std::size_t)
 
(33 intermediate revisions by 13 users not shown)
Line 1: Line 1:
{{cpp/title|make_unique}}
+
{{cpp/title|make_unique|make_unique_for_overwrite}}
 
{{cpp/memory/unique_ptr/navbar}}
 
{{cpp/memory/unique_ptr/navbar}}
 
{{dcl begin}}
 
{{dcl begin}}
{{dcl header | memory}}
+
{{dcl header|memory}}
{{dcl | num=1 | notes={{mark since c++14}}<br/>{{mark|only for non-array types}} |
+
{{dcl rev multi|num=1|anchor=1
 +
|since1=c++14|notes1={{mark|only for non-array types}}|dcl1=
 
template< class T, class... Args >
 
template< class T, class... Args >
 
unique_ptr<T> make_unique( Args&&... args );
 
unique_ptr<T> make_unique( Args&&... args );
 +
|since2=c++23<!--P2273R3-->|notes2={{mark|only for non-array types}}|dcl2=
 +
template< class T, class... Args >
 +
constexpr unique_ptr<T> make_unique( Args&&... args );
 
}}
 
}}
{{dcl | num=2 | notes={{mark since c++14}}<br/>{{mark|only for array types with unknown bound}} |
+
{{dcl rev multi|num=2
 +
|since1=c++14|notes1={{mark|only for array types with unknown bound}}|dcl1=
 
template< class T >
 
template< class T >
 
unique_ptr<T> make_unique( std::size_t size );
 
unique_ptr<T> make_unique( std::size_t size );
 +
|since2=c++23<!--P2273R3-->|notes2={{mark|only for array types with unknown bound}}|dcl2=
 +
template< class T >
 +
constexpr unique_ptr<T> make_unique( std::size_t size );
 
}}
 
}}
{{dcl | num=3  
+
{{dcl|num=3|since=c++14|notes={{mark|only for array types with known bound}}|1=
| notes={{mark since c++14}}<br/>{{mark|only for array types with known bound}} | 1=
+
 
template< class T, class... Args >
 
template< class T, class... Args >
 
/* unspecified */ make_unique( Args&&... args ) = delete;
 
/* unspecified */ make_unique( Args&&... args ) = delete;
 +
}}
 +
{{dcl rev multi|num=4|anchor=4
 +
|since1=c++20|notes1={{mark|only for non-array types}}|dcl1=
 +
template< class T >
 +
unique_ptr<T> make_unique_for_overwrite();
 +
|since2=c++23<!--P2273R3-->|notes2={{mark|only for non-array types}}|dcl2=
 +
template< class T >
 +
constexpr unique_ptr<T> make_unique_for_overwrite();
 +
}}
 +
{{dcl rev multi|num=5
 +
|since1=c++20|notes1={{mark|only for array types with unknown bound}}|dcl1=
 +
template< class T >
 +
unique_ptr<T> make_unique_for_overwrite( std::size_t size );
 +
|since2=c++23<!--P2273R3-->|notes2={{mark|only for array types with unknown bound}}|dcl2=
 +
template< class T >
 +
constexpr unique_ptr<T> make_unique_for_overwrite( std::size_t size );
 +
}}
 +
{{dcl|num=6|since=c++20|notes={{mark|only for array types with known bound}}|1=
 +
template< class T, class... Args >
 +
/* unspecified */ make_unique_for_overwrite( Args&&... args ) = delete;
 
}}
 
}}
 
{{dcl end}}
 
{{dcl end}}
Line 20: Line 47:
 
Constructs an object of type {{tt|T}} and wraps it in a {{lc|std::unique_ptr}}.
 
Constructs an object of type {{tt|T}} and wraps it in a {{lc|std::unique_ptr}}.
  
@1@ Constructs a non-array type {{tt|T}}. The arguments {{tt|args}} are passed to the constructor of {{tt|T}}. {{cpp/enable_if|{{tt|T}} is not an array type}}. The function is equivalent to:
+
@1@ Constructs a non-array type {{tt|T}}. The arguments {{c|args}} are passed to the constructor of {{tt|T}}. {{cpp/enable_if|{{tt|T}} is not an array type}}. The function is equivalent to:
 
{{source|unique_ptr<T>(new T(std::forward<Args>(args)...))}}
 
{{source|unique_ptr<T>(new T(std::forward<Args>(args)...))}}
  
@2@ Constructs an array of unknown bound {{tt|T}}. {{cpp/enable_if|{{tt|T}} is an array of unknown bound}}. The function is equivalent to:
+
@2@ Constructs an array of the given dynamic size. The array elements are [[cpp/language/value_initialization|value-initialized]]. {{cpp/enable_if|{{tt|T}} is an array of unknown bound}}. The function is equivalent to:
{{source|unique_ptr<T>(new typename std::remove_extent<T>::type[size]())}}
+
{{source|unique_ptr<T>(new std::remove_extent_t<T>[size]())}}
  
@3@ Construction of arrays of known bound is disallowed.
+
@3,6@ Construction of arrays of known bound is disallowed.
 +
 
 +
@4@ Same as {{v|1}}, except that the object is [[cpp/language/default_initialization|default-initialized]]. {{cpp/enable_if|{{tt|T}} is not an array type}}. The function is equivalent to:
 +
{{source|unique_ptr<T>(new T)}}
 +
 
 +
@5@ Same as {{v|2}}, except that the array is default-initialized. {{cpp/enable_if|{{tt|T}} is an array of unknown bound}}. The function is equivalent to:
 +
{{source|unique_ptr<T>(new std::remove_extent_t<T>[size])}}
  
 
===Parameters===
 
===Parameters===
 
{{par begin}}
 
{{par begin}}
{{par | args | list of arguments with which an instance of {{tt|T}} will be constructed.}}
+
{{par|args|list of arguments with which an instance of {{tt|T}} will be constructed}}
{{par | size | the size of the array to construct}}
+
{{par|size|the length of the array to construct}}
 
{{par end}}
 
{{par end}}
  
Line 41: Line 74:
  
 
===Possible Implementation===
 
===Possible Implementation===
{{eq fun
+
{{eq impl
| 1=
+
|title1=make_unique {{v|1-3}}|ver1=1|1=
// note: this implementation does not disable this overload for array types
+
// C++14 make_unique
template<typename T, typename... Args>
+
namespace detail
std::unique_ptr<T> make_unique(Args&&... args)
+
{
 +
    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)...));
 
     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;
 +
|title2=make_unique_for_overwrite {{v|4-6}}|ver2=4|2=
 +
// 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;
 
}}
 
}}
  
 
===Notes===
 
===Notes===
Unlike {{lc|std::make_shared}} (which has {{lc|std::allocate_shared}}), {{tt|std::make_unique}} does not have an allocator-aware counterpart. A hypothetical {{tt|allocate_unique}} would be required to invent the deleter type {{tt|D}} for the {{tt|unique_ptr<T,D>}} it returns which would contain an allocator object and invoke both {{tt|destroy}} and {{tt|deallocate}} in its {{tt|operator()}}.
+
Unlike {{lc|std::make_shared}} (which has {{lc|std::allocate_shared}}), {{tt|std::make_unique}} does not have an allocator-aware counterpart. {{tt|allocate_unique}} proposed in {{wg21|P0211}} would be required to invent the deleter type {{tt|D}} for the {{c|std::unique_ptr<T,D>}} it returns which would contain an allocator object and invoke both {{tt|destroy}} and {{tt|deallocate}} in its {{c|operator()}}.
 +
 
 +
{{ftm begin|std=1|comment=1}}
 +
{{ftm|std=C++14|value=201304L|__cpp_lib_make_unique|{{tt|std::make_unique}}; overload {{v|1|1}}}}
 +
{{ftm|std=C++20|value=202002L|__cpp_lib_smart_ptr_for_overwrite|Smart pointer creation with default initialization ({{lc|std::allocate_shared_for_overwrite}}, {{lc|std::make_shared_for_overwrite}}, {{tt|std::make_unique_for_overwrite}}); overloads {{v|4-6|4}}}}
 +
{{ftm|std=C++23|value=202202L|__cpp_lib_constexpr_memory|{{tt|constexpr}} for overloads {{v|1,2,4,5|1}}}}
 +
{{ftm end}}
  
 
===Example===
 
===Example===
 +
{{todo|add more {{c|make_unique_for_overwrite()}} demos}}
 
{{example
 
{{example
|
+
|code=
| code=
+
#include <cstddef>
 +
#include <iomanip>
 
#include <iostream>
 
#include <iostream>
 
#include <memory>
 
#include <memory>
 +
#include <utility>
  
 
struct Vec3
 
struct Vec3
 
{
 
{
 
     int x, y, z;
 
     int x, y, z;
     Vec3() : x(0), y(0), z(0) { }
+
 
     Vec3(int x, int y, int z) :x(x), y(y), z(z) { }
+
     // Following constructor is no longer needed since C++20.
     friend std::ostream& operator<<(std::ostream& os, Vec3& v) {
+
     Vec3(int x = 0, int y = 0, int z = 0) noexcept : x(x), y(y), z(z) {}
         return os << '{' << "x:" << v.x << " y:" << v.y << " z:" << v.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()
 
int main()
Line 75: Line 175:
 
     // Use the default constructor.
 
     // Use the default constructor.
 
     std::unique_ptr<Vec3> v1 = std::make_unique<Vec3>();
 
     std::unique_ptr<Vec3> v1 = std::make_unique<Vec3>();
     // Use the constructor that matches these arguments
+
     // Use the constructor that matches these arguments.
 
     std::unique_ptr<Vec3> v2 = std::make_unique<Vec3>(0, 1, 2);
 
     std::unique_ptr<Vec3> v2 = std::make_unique<Vec3>(0, 1, 2);
     // Create a unique_ptr to an array of 5 elements
+
     // Create a unique_ptr to an array of 5 elements.
 
     std::unique_ptr<Vec3[]> v3 = std::make_unique<Vec3[]>(5);
 
     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'
 
     std::cout << "make_unique<Vec3>():      " << *v1 << '\n'
 
               << "make_unique<Vec3>(0,1,2): " << *v2 << '\n'
 
               << "make_unique<Vec3>(0,1,2): " << *v2 << '\n'
               << "make_unique<Vec3[]>(5):  " << '\n';
+
               << "make_unique<Vec3[]>(5):  ";
     for (int i = 0; i < 5; i++) {
+
    for (std::size_t i = 0; i < 5; ++i)
         std::cout << "     " << v3[i] << '\n';
+
        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";
 
}
 
}
| output=
+
|output=
make_unique<Vec3>():      {x:0 y:0 z:0}
+
make_unique<Vec3>():      { x=0, y=0, z=0 }
make_unique<Vec3>(0,1,2): {x:0 y:1 z:2}
+
make_unique<Vec3>(0,1,2): { x=0, y=1, z=2 }
make_unique<Vec3[]>(5):   
+
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 }
    {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]
 
}}
 
}}
  
 
===See also===
 
===See also===
 
{{dsc begin}}
 
{{dsc begin}}
{{dsc inc | cpp/memory/unique_ptr/dsc constructor}}
+
{{dsc inc|cpp/memory/unique_ptr/dsc constructor}}
{{dsc inc | cpp/memory/shared_ptr/dsc make_shared}}
+
{{dsc inc|cpp/memory/shared_ptr/dsc make_shared}}
 
{{dsc end}}
 
{{dsc end}}
  
{{langlinks|zh}}
+
{{langlinks|de|es|ja|ru|zh}}

Latest revision as of 10:56, 10 October 2023

 
 
Utilities library
General utilities
Relational operators (deprecated in C++20)
 
Dynamic memory management
Uninitialized memory algorithms
Constrained uninitialized memory algorithms
Allocators
Garbage collection support
(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)



 
 
Defined in header <memory>
(1)
template< class T, class... Args >
unique_ptr<T> make_unique( Args&&... args );
(since C++14)
(until C++23)
(only for non-array types)
template< class T, class... Args >
constexpr unique_ptr<T> make_unique( Args&&... args );
(since C++23)
(only for non-array types)
(2)
template< class T >
unique_ptr<T> make_unique( std::size_t size );
(since C++14)
(until C++23)
(only for array types with unknown bound)
template< class T >
constexpr unique_ptr<T> make_unique( std::size_t size );
(since C++23)
(only for array types with unknown bound)
template< class T, class... Args >
/* unspecified */ make_unique( Args&&... args ) = delete;
(3) (since C++14)
(only for array types with known bound)
(4)
template< class T >
unique_ptr<T> make_unique_for_overwrite();
(since C++20)
(until C++23)
(only for non-array types)
template< class T >
constexpr unique_ptr<T> make_unique_for_overwrite();
(since C++23)
(only for non-array types)
(5)
template< class T >
unique_ptr<T> make_unique_for_overwrite( std::size_t size );
(since C++20)
(until C++23)
(only for array types with unknown bound)
template< class T >
constexpr unique_ptr<T> make_unique_for_overwrite( std::size_t size );
(since C++23)
(only for array types with unknown bound)
template< class T, class... Args >
/* unspecified */ make_unique_for_overwrite( Args&&... args ) = delete;
(6) (since C++20)
(only for array types with known bound)

Constructs an object of type T and wraps it in a std::unique_ptr.

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)...))
2) 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]())
3,6) Construction of arrays of known bound is disallowed.
4) 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)
5) 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])

Contents

[edit] Parameters

args - list of arguments with which an instance of T will be constructed
size - the length of the array to construct

[edit] Return value

std::unique_ptr of an instance of type T.

[edit] 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.

[edit] Possible Implementation

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;

[edit] Notes

Unlike std::make_shared (which has std::allocate_shared), std::make_unique does not have an allocator-aware counterpart. allocate_unique proposed in P0211 would be required to invent the deleter type D for the std::unique_ptr<T,D> it returns which would contain an allocator object and invoke both destroy and deallocate in its operator().

Feature-test macro Value Std Feature
__cpp_lib_make_unique 201304L (C++14) std::make_unique; overload (1)
__cpp_lib_smart_ptr_for_overwrite 202002L (C++20) Smart pointer creation with default initialization (std::allocate_shared_for_overwrite, std::make_shared_for_overwrite, std::make_unique_for_overwrite); overloads (4-6)
__cpp_lib_constexpr_memory 202202L (C++23) constexpr for overloads (1,2,4,5)

[edit] Example

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

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]

[edit] See also

constructs a new unique_ptr
(public member function) [edit]
creates a shared pointer that manages a new object
(function template) [edit]