经过一段时间的调试,我们发现deque这个容器中的pop_front方法存在内存泄漏,在VS2008的环境下面。
查看VS2008的source code如下:
void pop_front()
{ // erase element at beginning
#if _HAS_ITERATOR_DEBUGGING
if (empty())
_DEBUG_ERROR("deque empty before pop");
else
{ // something to erase, do it
_Orphan_off(_Myoff);
#else /* _HAS_ITERATOR_DEBUGGING */
if (!empty())
{ // something to erase, do it
#endif /* _HAS_ITERATOR_DEBUGGING */
size_type _Block = _Myoff / _DEQUESIZ;
this->_Alval.destroy(_Map[_Block] + _Myoff % _DEQUESIZ);
if (_Mapsize * _DEQUESIZ <= ++_Myoff)
_Myoff = 0;
if (--_Mysize == 0)
_Myoff = 0;
}
}
在pop_front方法中,只调用了destroy方法,而没有调用deallocate方法,所以这块内存没有被释放。我们知道deque的实现方法类似于vector,它们都是内部是动态数组的形式实现的。
尽管C++ 98 的文档说明:If an element is erased at the front of the deque, only that iterator and references to the erased element become invalid,这里也没有提到释放内存的操作。然而在VC6.0和VS2010中,pop_front都实现了在pop_front中调用deallocate这个方法来释放内存。
而在C++ 11 标准中,deque新增加了一个shrink_to_fit方法来释放内存。。。。
这种版本之间的不一致,很坑人呀。。。。
参考文档: