【问题标题】:Insert and push_back a pointer to a vector of unique pointers give different compilation behavior?插入和 push_back 指向唯一指针向量的指针会产生不同的编译行为吗?
【发布时间】:2012-12-26 17:22:06
【问题描述】:

我的代码如下

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)会显示差异?谢谢。

【问题讨论】:

标签: c++ vector c++11 unique-ptr


【解决方案1】:

这是因为在 VS2010 中,v.insert(v.end(), new int(1)); 被优化为 callstd::vector::emplace_back 构造对象,而 std::vector::push_back 将尝试将 int* 复制/转换为 std::unique_ptr&lt;int&gt; 然后它失败了。要将智能指针推送到 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));,但 emplace_back 在这两种情况下都有效。

【讨论】:

  • 对于您提供的三个选项,哪个更快?或者他们是一样的?谢谢。
  • 我不认为 emplace back 方法是安全的。新的 int(1) 调用可以成功,然后如果向量需要增长,则可能会失败,这将引发异常。我认为抛出发生在新的 int(1) 调用之后但在创建 unique_ptr 之前因此导致内存泄漏。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-04
  • 2017-11-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-02
相关资源
最近更新 更多