c++ - 有什么方法可以初始化 unique_ptr 的 vector 吗?

标签 c++ c++11 initialization unique-ptr initializer-list

例如

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 of N elements of type const 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 the std::initializer_list<E> object is constructed to refer to that array.

只能复制,不能复制一个unique_ptr因为它只能移动。

你必须使用 push_backemplace_back等在构建之后填充 vector 。

关于c++ - 有什么方法可以初始化 unique_ptr 的 vector 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25827435/

相关文章:

c++ - 基类中的抽象基成员变量

java - C服务器和Java客户端之间的UDP连接

c++ - 为什么我不能使用 strerror?

c++ - 在 C++ 中创建对三元运算符结果的 const 引用是否安全?

c++ - 有没有办法在继承构造函数时访问初始化列表?

linux - 在 linux/OS X 上启动 mongod 服务的正确方法是什么?

c++ - 在 g++ 中使用 __attribute__ 的不平衡括号

c++ - Rvalue 成员确实也是 Rvalues 吗?

c++ - 将可变参数模板传递给 pthread_create

java - 字符串因未知原因被初始化为 0