标准库字符串的新位置出现内存泄漏 [英] Memory leak in placement new of standard library string
本文介绍了标准库字符串的新位置出现内存泄漏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在放置新的标准库字符串时遇到内存泄漏。
下面我给出了显示泄漏的代码。
string string1("new string");
char _string[sizeof(string)];
new(_string) string(string1);
使用Dbx发现泄漏,如下所示
Actual leaks report (actual leaks: 1 total size: 52 bytes)
Total Num of Leaked Allocation call stack
Size Blocks Block
Address
========== ====== =========== =======================================
52 1 0x43f68 operator new < std::basic_string<char,std::char_traits<char>,std::allocator<char> >::__getRep < std::basic_string<char,std::char_traits<char>,std::allocator<char> >::basic_string < main
Possible leaks report (possible leaks: 0 total size: 0 bytes)
这是真正的内存泄漏,还是DBX将其理解为泄漏?
推荐答案
您仍然需要为Placement New创建的字符串对象调用析构函数。
std::string
为它在堆上存储的字符分配存储空间(除非您指定了一个定制分配器,这可能就是您在这里要做的事情),而您正在泄漏这一点。(sizeof(string)
是一个常量,与字符串中存储的内容无关。)
这篇关于标准库字符串的新位置出现内存泄漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文