使用赋值运算符的的unique_ptr
问题描述:
矢量如果我有std::unique_ptr
的std::vector
和调整其大小,并希望通过指数来添加元素,什么是使用operator=
增加他们的最好方法是什么?使用赋值运算符的的unique_ptr
std::vector<std::unique_ptr<item>> _v;
_v.resize(100);
// is it safe to use the assignment operator?
_v[20] = new item;
答
你可以,如果你使用的是C++ 14,像
_v[20] = std::make_unique<item>(/* Args */);
使用
std::make_unique
否则,如果你在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>();
+2
请注意'std :: make_unique()'是在C++ 14中添加的。对于C++ 11,可以使用'_v [20] = std :: unique_ptr
你认为有很多方法可供选择吗? – 2017-10-20 18:47:41
大多数教程都讨论了如何使用unique_ptr的方法以及如何避免仅仅确保=运算符没有缺点。 – devcodexyz
请注意前面的下划线。它们通常被保留供图书馆实施使用。 方便阅读:[在C++标识符中使用下划线的规则是什么?](https://stackoverflow.com/questions/228783/what-are-the-rules-about-using-an-underscore-in- ac-identifier) – user4581301