c++ - VS2013 下的 emplace_back() 问题

标签 c++ c++11 gcc visual-studio-2013

考虑以下代码

std::vector<int> nums{21, 22, 23, 24};
nums.emplace_back(nums[0]);
nums.emplace_back(nums[1]);

for (auto n : nums) {
    std::cout << n << std::endl;
}

VS2013

的输出
21
22
23
24
-17891602
22

为什么-17891602在这里?

GCC 4.8.4的输出正确如下

21
22
23
24
21
22

那我比较VS2013GCC

emplace_back的实现

VS2013

template<class... _Valty>
    void emplace_back(_Valty&&... _Val)
    {   // insert by moving into element at end
    if (this->_Mylast == this->_Myend)
        _Reserve(1);
    _Orphan_range(this->_Mylast, this->_Mylast);
    this->_Getal().construct(this->_Mylast,
        _STD forward<_Valty>(_Val)...);
    ++this->_Mylast;
    }

海合会

template<typename _Tp, typename _Alloc>
template<typename... _Args>
  void
  vector<_Tp, _Alloc>::
  emplace_back(_Args&&... __args)
  {
    if (this->_M_impl._M_finish != this->_M_impl._M_end_of_storage)
      {
        _Alloc_traits::construct(this->_M_impl, this->_M_impl._M_finish,
                                 std::forward<_Args>(__args)...);
        ++this->_M_impl._M_finish;
      }
    else
      _M_emplace_back_aux(std::forward<_Args>(__args)...);
  }

VS2013 中似乎使用了奇怪的 _Reserve(1);。为什么?

编辑:

-17891602hex值为0xFEEEFEEE,表示

Used by Microsoft's debug HeapFree() to mark freed heap memory

请参阅 magic number

然后我逐行调试上面的代码,发现_Reserve(1);调用引起的0XFEEEFEEE

最佳答案

这是 VS2013 和 VS2015 在将元素放置到包含该元素的 vector 时的问题。如果 vector 调整大小,则对插入元素的引用无效。解决方法是在插入中创建元素的拷贝,然后将其插入。

auto n = nums[0];
nums.emplace_back(n);

_Reserve 调用是为了确保为 vector 分配了一些内存(因此不必在以后的操作中检查它)。

关于c++ - VS2013 下的 emplace_back() 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34585575/

相关文章:

c++ - 错误 : 'hash' is not a class template

c++ - 使用 braced-init 初始化 std::shared_ptr<std::map<>>

c++ - 根据标准,这些编译器中的哪个有错误?

c++ - Clang 不会编译 gcc 会编译的模板特化

C++运算符重载无法输出+运算

c++ - 进程崩溃时如何释放boost::interprocess::named_mutex

带有静态成员的 c++ std::thread 挂起

c++ - 如何获取列表中的倒数第二个元素?

c++ - 指向不同类成员函数的指针

c++ - 在 G++ 4.8 中,typeof 仍然不能与 "::"一起使用