如何用unique_ptr初始化结构的向量?例如:
#include <memory>
#include <vector>
using namespace std;
struct A
{
int i;
unique_ptr<int> p;
};
int main()
{
vector<A> v{ { 10, make_unique<int>(10) } };
// error above: cannot convert from initializer-list to vector<A>
return 0;
}发布于 2014-04-03 00:26:54
vector<A> v{ { 10, make_unique<int>(10) } };在上面语句的内部大括号中,您正在聚合地初始化A的一个实例,到目前为止还不错。
但是现在没有办法将这个实例从初始化程序列表中移出,您唯一能做的就是复制对象。但是,复制将失败,因为编译器为A生成的复制构造函数由于unique_ptr数据成员而被隐式删除。因此产生了编译错误。
唯一的解决办法就是不要使用带括号的列表。相反,构造一个A实例,然后使用
v.push_back(std::move(a));https://stackoverflow.com/questions/22825399
复制相似问题