假设我想创建一个std::unique_ptr<int[]>,但我想将创建的数组初始化为自定义值:{1,2,3,4,5}。
我可以使用new原始指针并将其传递给std::unique_ptr构造函数,然后构造函数将拥有并管理它。
std::unique_ptr<int[]> ptr{ new int[5]{1,2,3,4,5} };
Run Code Online (Sandbox Code Playgroud)
我的问题是,可以以某种方式完成同样的事情std::make_unique吗?
有 3 个重载std::make_unique:
template< class T, class... Args >
unique_ptr<T> make_unique( Args&&... args ); // (1) for non-array type
template< class T >
unique_ptr<T> make_unique( std::size_t size ); // (2) for array type with unknown bounds
template< class T, class... Args >
/* unspecified */ make_unique( Args&&... args ) = delete; // (3) for array type with known bounds.
Run Code Online (Sandbox Code Playgroud)
它们都不支持您想要的行为(请注意,第三个函数被标记为delete)。
您可以使用(2)并单独初始化数组元素,或切换到std::vector并使用(1)。