例如
struct A
{
vector<unique_ptr<int>> m_vector { make_unique<int>(1), make_unique<int>(2) };
};
我尝试了以上但失败了。有什么方法可以初始化 unique_ptr 的 vector ?
最佳答案
您不能从初始化列表中移动,因为元素是 const
. §8.5.4 [dcl.init.list]/p5:
An object of type
std::initializer_list<E>
is constructed from an initializer list as if the implementation allocated an array ofN
elements of typeconst E
, where N is the number of elements in the initializer list. Each element of that array is copy-initialized with the corresponding element of the initializer list, and thestd::initializer_list<E>
object is constructed to refer to that array.
只能复制,不能复制一个unique_ptr
因为它只能移动。
你必须使用 push_back
或 emplace_back
等在构建之后填充 vector 。
关于c++ - 有什么方法可以初始化 unique_ptr 的 vector 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25827435/