使用std::make_unique能否对动态数组进行花括号初始化?

3
通常,我们可以通过动态分配的花括号初始化来创建数组。
int* arr = new int[5]{1,1,2,4,5};

但是使用智能指针,特别是使用std::make_unique是否可能实现这一点呢?我尝试了以下代码:
unique_ptr<int[]> arr(5) {1,1,2,4,5};
unique_ptr<int[]> arr = make_unique<int[]>(5){1,1,2,4,5};
unique_ptr<int[]> arr = make_unique<int[]>({1,1,2,4,5});

但是没有用,我已经到了一个认为使用智能指针可能根本不可能的地步。有没有关于如何使用花括号初始化智能指针的建议将不胜感激。

是的,我知道std::vector,但希望有另一种选择。

1个回答

5

使用智能指针,特别是使用 std::make_unique,是否可能实现这一点?

不行,你不能使用 std::make_unique 来完成此操作,因为它对数组有特殊的实现,并且仅限于未知大小。

根据 cppreference.com,对于未知大小std::make_unique 只有一个重载2

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

  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.
这意味着,在您的情况下,它将创建给定大小的动态数组,并将整数初始化为0,不能传递初始化值。
任何有关使用大括号初始化智能指针的建议都将不胜感激。您可以不使用std::make_unique,类似这样:
std::unique_ptr<int[]> arr{ new int[]{1, 1, 2, 4, 5} };

或者编写自己的make_unique函数,它将创建一个动态数组,该数组的元素类型与您传递的相同,并使用您传递的值进行初始化。
#include <memory>
#include <type_traits>  // std::common_type

template<typename... Args>
auto make_unique_init(Args&&... args)
{
    using Type = std::common_type_t<Args...>;
    return std::unique_ptr<Type[]>(new Type[sizeof...(args)]{ std::forward<Args>(args)... });
}

现在你可以写:

std::unique_ptr<int[]> arr2 = make_unique_and_init(1, 1, 2, 4, 5);

这里是一个 工作示例代码


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接