加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 任何初始化unique_ptr向量的方法?

发布时间:2020-12-16 09:54:10 所属栏目:百科 来源:网络整理
导读:例如 struct A{ vectorunique_ptrint m_vector { make_uniqueint(1),make_uniqueint(2) };}; 我尝试上面但失败了.有什么方法可以初始化unique_ptr的向量? 解决方法 您无法从初始化列表移动,因为元素是const. §8.5.4[dcl.init.list] / p5: An object of ty
例如

struct A
{
    vector<unique_ptr<int>> m_vector { make_unique<int>(1),make_unique<int>(2) };
};

我尝试上面但失败了.有什么方法可以初始化unique_ptr的向量?

解决方法

您无法从初始化列表移动,因为元素是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_back或emplace_back等来填充向量.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读