std::make_unique, std::make_unique_for_overwrite
Определено в заголовке <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 > /* unspecified */ 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 > /* unspecified */ make_unique_for_overwrite( Args&&... args ) = delete; | (6) | (с C++20) (только для типов-массивов с известной длиной) |
Создаёт объект типа T и оборачивает его в std::unique_ptr.
T. Аргументы args передаются в конструктор T. Этот перегруз участвует в разрешении перегрузки только если T не является типом массива. Функция эквивалентна: unique_ptr<T>(new T(std::forward<Args>(args)...))
T является массивом с неопределённой длиной. Функция эквивалентна: unique_ptr<T>(new std::remove_extent_t<T>[size]())
T не является типом массива. Функция эквивалентна: unique_ptr<T>(new T)
T является массивом с неопределённой длиной. Функция эквивалентна: unique_ptr<T>(new std::remove_extent_t<T>[size])
Параметры
| args | - | список аргументов, с помощью которых будет создан экземпляр T |
| size | - | длина создаваемого массива |
Возвращаемое значение
Указатель на экземпляр типа T.
Исключения
Может выбросить std::bad_alloc или любое исключение, выброшенное конструктором T. Если выброшено исключение, функция не имеет эффекта.
Возможная реализация
| 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 нет аналога, учитывающего аллокатор. allocate_unique, предложенный в P0211, потребовало бы изобретение типа удалителя D для std::unique_ptr<T,D> возвращаемого ей, который содержал бы объект аллокатора и вызывал бы как destroy, так и deallocate в своём operator().
| Макросы проверки наличия функции | Значение | Стандарт | Функция |
|---|---|---|---|
__cpp_lib_make_unique | 201304L | (C++14) |
std::make_unique; перегрузка (1) |
__cpp_lib_smart_ptr_for_overwrite | 202002L | (C++20) | Создание умных указателей с инициализацией по умолчанию (std::allocate_shared_for_overwrite, std::make_shared_for_overwrite, std::make_unique_for_overwrite); перегрузки (4-6) |
__cpp_lib_constexpr_memory | 202202L | (C++23) |
constexpr для перегрузок (1,2,4,5) |
Пример
#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 (публичный член-функция) |
|
|
(C++20) | создаёт умный указатель, управляющий новым объектом (шаблон функции) |
© cppreference.com
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.
https://en.cppreference.com/w/cpp/memory/unique_ptr/make_unique