将赋值运算符与 unique_ptr 向量一起使用

Using assignment operator with vector of unique_ptr

本文关键字:向量 一起 ptr 赋值运算符 unique      更新时间:2023-10-16

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

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

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 */));
std::unique_ptr没有

采用原始指针的赋值运算符。

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

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