use*_*020 5 c++ initialization c++11
例如
struct A
{
vector<unique_ptr<int>> m_vector { make_unique<int>(1), make_unique<int>(2) };
};
Run Code Online (Sandbox Code Playgroud)
我尝试上面但失败了.有什么方法可以初始化unique_ptr的向量?
您无法从初始化列表中移动,因为元素是const.§8.5.4[dcl.init.list]/p5:
类型的对象
std::initializer_list<E>是从初始化列表构造的,就好像实现分配了一个N类型的元素数组const E,其中N是初始化列表中元素的数量.使用初始化列表的相应元素对该数组的每个元素进行复制初始化,并std::initializer_list<E>构造该 对象以引用该数组.
您只能复制,但不能复制,unique_ptr因为它只是移动.
在构造向量之后,您必须使用push_back或emplace_back等来填充向量.