std :: vector <std :: unique_ptr <>> :: push_back()的正确语法是什么?

路易斯·舒曼

我已经读过,unique_ptr如果要使用push_backfrom ,需要为a定义一个删除器std::vector<std::unique_ptr<T>>真的吗?如果是,执行此操作的正确语法是什么?

谢谢您的回答

暗影游侠

不,通常情况下不需要自定义删除器。对于现有的unique_ptr

vector.push_back(std::move(ptr));

工作正常(将指针的所有权转让给vector);对于新的指针:

vector.push_back(std::make_unique<MyType>(args, go, here));

是最安全的(因为它确保始终管理指针,即使push_back抛出异常也是如此),它具有:

vector.emplace_back(new MyType(args, go, here));

可能会更快一些,但如果vector引发异常(例如由于扩展基础存储的尝试失败)而以潜在的内存泄漏为代价;尽管在这种情况下,您的程序可能仍然注定要失败,所以它可能不值得捍卫反对)。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

将std :: unique_ptr推回std :: vector时,编译器不会失败

为什么std :: unique_ptr :: reset()总是noexcept?

std :: move()之后,unique_ptr会发生什么?

调整大小std :: vector <std :: unique_ptr <T >>的性能

声明包含std :: unique_ptr的结构的std :: vector类时出错

std :: unique_ptr和std :: shared_ptr之间的破坏行为差异的原理是什么?

为什么std :: shared_ptr <T> = std :: unique_ptr <T []>可以编译,而std :: shared_ptr <T []> = std :: unique_ptr <T []>不可以编译?

是否可以使用fill构造函数创建std :: vector <std :: unique_ptr <Bar >>?

std :: unique_ptr :: release()与std :: move()

与std :: shared_ptr和std :: unique_ptr相比,std :: optional`有什么优势?

std :: remove_if来自std :: vector的多态std :: unique_ptr

使用什么std :: optional或std :: unique_ptr

为什么std :: unique_ptr重设与赋值不同?

使用std :: unique_ptr <T>&代替std :: unique_ptr <T>有什么优势吗?

C ++-vector <>中的std :: unique_ptr为nullptr

为什么我不能使用{std :: move(first),std :: move(second)}实例化std :: vector <std :: unique_ptr <int >>?

将std :: vector <std :: unique_ptr <T >>分配给另一个std :: vector <std :: unique_ptr <T >>

使用`std :: unique_ptr`时`std :: vector`中的数据不同

std :: vector中push_back函数的奇怪语法

使用std :: vector <double>访问由std :: unique_ptr <double [2]>管理的数据

如何检查std :: unique_ptr是否为空(如果它位于std :: vector中)?

如何调整std :: vector <std :: queue <std :: unique_ptr <int >>>的大小?

构造类成员std :: vector <std :: unique_ptr <AClass>的智能方法

还有什么更好的替代std :: vector <std :: unique_ptr <T >>吗?

std :: vector <std :: unique_ptr <int>>不编译

'operator[]' 不匹配(操作数类型是 'std::unique_ptr<std::vector<int> >' 和 'int')

为什么我需要移动 `std::unique_ptr`

在 unique_ptr 向量中使用 push_back(std::move())

std::unique_ptr 中 operator* 的 const 正确性