插入一个指向唯一指针向量的指针并将其推回(_back),会产生不同的编译行为

Insert and push_back a pointer to a vector of unique pointers give different compilation behavior?

本文关键字:指针 back 编译 一个 唯一 插入 向量      更新时间:2023-10-16

我有如下代码

vector<unique_ptr<int>> v;
v.insert(v.end(), new int(1)); // this is okay
v.push_back(new int(1)); // this is wrong, cannot convert int* to unique_ptr<int>&&

为什么汇编(vc2010(显示了差异?谢谢

这是因为在VS2010中,v.insert(v.end(), new int(1));被优化为调用在适当位置构造对象的std::vector::emplace_back,而std::vector::push_back将尝试将int*复制/转换为std::unique_ptr<int>,然后失败。要将智能指针推入STL容器,您可以指定确切的类型:

v.insert(v.end(), unique_ptr<int>(new int(1))); 
v.push_back(unique_ptr<int>(new int(1))); 

或者简单地调用

v.emplace_back(new int(1));

我已经在VS2010和VS2012上测试了您的代码,说明VS2012服务器不允许v.insert(v.end(), new int(1));,但template_back在这两种情况下都有效。