C++ 使用具有唯一_ptr向量的赋值运算符

C++ 使用具有唯一_ptr向量的赋值运算符,c++,memory,vector,std,C++,Memory,Vector,Std,如果我有一个std::vector的std::unique\u ptr并调整其大小,并且希望按索引添加元素,那么使用操作符=添加它们的最佳方法是什么 std::vector<std::unique_ptr<item>> _v; _v.resize(100); // is it safe to use the assignment operator? _v[20] = new item; std::vector\u v; _v、 调整大小(100); //使用赋值运算符

如果我有一个
std::vector
std::unique\u ptr
并调整其大小,并且希望按索引添加元素,那么使用
操作符=
添加它们的最佳方法是什么

std::vector<std::unique_ptr<item>> _v;
_v.resize(100);
// is it safe to use the assignment operator? 
_v[20] = new item;
std::vector\u v;
_v、 调整大小(100);
//使用赋值运算符是否安全?
_v[20]=新项目;

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

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

\u v[20]=std::make_unique();
如果您使用的是C++14,您可以使用

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

你认为有很多方法可供选择吗?大多数教程都谈到如何使用unique_ptr,以及如何避免使用=运算符的缺点。注意前面的下划线。它们通常保留供库实现使用。方便阅读:@MoradMohammad如答案中所述,以示例中所示的方式使用赋值运算符有一个缺点:。请注意,
std::make_unique()
是在C++14中添加的。对于C++11,可以使用
\u v[20]=std::unique\u ptr(新项)取而代之。
_v[20] = std::make_unique<item>(/* Args */);
_v[20] = std::unique_ptr<item>(new item(/* Args */));