我正在使用一个vector容器来保存包含3个整数和2个std::string
的对象的实例,这是在堆栈上创build的,并从另一个类的函数中填充,但通过deleaker运行应用程序显示std::string
从对象的std::string
s都泄漏。 代码如下:
// Populator function: void PopulatorClass::populate(std::vector<MyClass>& list) { // m_MainList contains a list of pointers to the master objects for( std::vector<MyClass*>::iterator it = m_MainList.begin(); it != m_MainList.end(); it++ ) { list.push_back(**it); } } // Class definition class MyClass { private: std::string m_Name; std::string m_Description; int m_nType; int m_nCategory; int m_nSubCategory; }; // Code causing the problem: std::vector<MyClass> list; PopulatorClass.populate(list);
当通过删除者运行时,泄漏的内存位于std::string
类的分配器中。
我正在使用Visual Studio 2010(CRT)。
有什么特别的,我需要做的,以便正确删除string
时,展开堆栈和删除vector
?
谢谢,J
每当你遇到一个STL实现的问题,像内存泄漏这样的奇怪或错误,试试这个 :
未针对您的特定问题测试简单的实时示例:
#include <string> #include <sstream> // Class definition struct MyClass { // struct for convenience std::string m_Name; std::string m_Description; int m_nType; int m_nCategory; int m_nSubCategory; }; // Prototype of populator function: void populate(std::vector<MyClass>& list) { const int MAX_TYPE_IDX = 4; const int MAX_CATEGORY_IDX = 8; const int MAX_SUB_CATEGORY_IDX = 6; for( int type_idx = 0; type_idx < MAX_TYPE_IDX ; ++type_idx) for( int category_idx = 0; category_idx < MAX_CATEGORY_IDX ; ++category_idx) for( int sub_category_idx = 0; sub_category_idx < MAX_SUB_CATEGORY_IDX ; ++sub_category_idx) { std::stringstream name_stream; name_stream << "object_" << type_idx << "_" << category_idx << "_" << sub_category_idx ; std::stringstream desc_stream; desc_stream << "This is an object of the type N°" << type_idx << ".\n"; desc_stream << "It is of category N°" << category_idx << ",\n"; desc_stream << "and of sub-category N°" << category_idx << "!\n"; MyClass object; object.m_Name = name_stream.str(); object.m_Description = desc_stream.str(); object.m_nType = type_idx; m_nCategory = m_nSubCategory = list.push_back( object ); } } int main() { // Code causing the problem: std::vector<MyClass> list; populate(list); // memory leak check? return 0; }
可能是内存泄漏与std::vector<std::string>
或类似的东西。
可能与阿列克谢的链接相同的根本问题。 发货版本已经破坏了basic_string的移动代码。 MS放弃了我们的VC10用户,所以你必须自己修复它。 在xstring文件中你有这个:
_Myt& assign(_Myt&& _Right) { // assign by moving _Right if (this == &_Right) ; else if (get_allocator() != _Right.get_allocator() && this->_BUF_SIZE <= _Right._Myres) *this = _Right; else { // not same, clear this and steal from _Right _Tidy(true); if (_Right._Myres < this->_BUF_SIZE) _Traits::move(this->_Bx._Buf, _Right._Bx._Buf, _Right._Mysize + 1); else { // copy pointer this->_Bx._Ptr = _Right._Bx._Ptr; _Right._Bx._Ptr = 0; } this->_Mysize = _Right._Mysize; this->_Myres = _Right._Myres; _Right._Mysize = 0; _Right._Myres = 0; } return (*this); }
注意最后一个
_Right._Myres = 0;
这应该只发生在最后的情况下,因为短小的情况下,最好不要放弃。
由于容量设置为0而不是15,所以当您分配另一个小字符串时,其他代码将在函数Grow()中进行意外分支,并将分配一块内存,以便用直接字符串内容对指针进行践踏。