插入一个指向唯一指针向量的指针并将其推回(_back),会产生不同的编译行为
Insert and push_back a pointer to a vector of unique pointers give different compilation behavior?
我有如下代码
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在这两种情况下都有效。
相关文章:
- 1d 智能指针不适用于语法 (*)++
- 在C#中处理C++指针而不使用unsafe的最佳方法
- 为什么使用 "this" 指针调用派生成员函数?
- 函数向量_指针有不同的原型,我可以构建一个吗
- 使用指针从C++中的数组中获取最大值
- 助记符和指向成员语法的指针
- 嵌入方指针压缩已禁用
- 数组的指针从不分段故障
- C++ 指针的内存地址和指向数组的内存地址如何相同?
- 何时在引用或唯一指针上使用移动语义
- QMetaObject invokeMethod的基于函数指针的语法
- 如何从 std::atomic 中提取指针 T<T>?
- 如何在 C# 中映射双 C 结构指针?
- C++将浮点指针值舍入为小数位数
- 为什么++(*p)更改指针值
- 调整大小后指向元素值的指针unordered_map有效?
- 正在将指针转换为范围
- 线路抑制状态错误 C4703 可能未初始化的局部指针变量"back"已使用
- push(ing)back在循环中对象指针
- 带有指针的push_back()和back()的行为