【问题标题】:Using assignment operator with vector of unique_ptr使用带有 unique_ptr 向量的赋值运算符
【发布时间】:2017-10-20 18:43:38
【问题描述】:

如果我有一个 std::vectorstd::unique_ptr 并调整它的大小,并想按索引添加元素,使用 operator= 添加它们的最佳方法是什么?

std::vector<std::unique_ptr<item>> _v;
_v.resize(100);
// is it safe to use the assignment operator? 
_v[20] = new item;

【问题讨论】:

  • 你觉得选择的方式有很多吗?
  • 大多数教程都在讨论如何使用 unique_ptr 以及如何避免只是确保 = 运算符没有缺点。
  • 注意前面的下划线。它们通常保留供库实现使用。方便阅读:What are the rules about using an underscore in a C++ identifier?
  • @MoradMohammad 如答案中所述,以您在示例中显示的方式使用赋值运算符存在一个缺点:it doesn't compile

标签: c++ memory vector std


【解决方案1】:

如果你使用 C++14,你可以使用 std::make_unique,就像那样

_v[20] = std::make_unique<item>(/* Args */);

否则如果你是C++14以下,可以自己实现std::make_unique,或者使用std::unique_ptr的构造函数

_v[20] = std::unique_ptr<item>(new item(/* Args */));

【讨论】:

    【解决方案2】:

    std::unique_ptr 没有接受原始指针的赋值运算符。

    但它确实有一个从另一个 std::unique_ptr 移动的赋值运算符,您可以使用 std::make_unique() 创建它:

    _v[20] = std::make_unique<item>();
    

    【讨论】:

    • 请注意,std::make_unique() 是在 C++14 中添加的。对于 C++11,您可以改用_v[20] = std::unique_ptr&lt;item&gt;(new item);
    猜你喜欢
    • 1970-01-01
    • 2018-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-23
    • 2013-12-08
    相关资源
    最近更新 更多