C++ 新标准库字符串放置中的内存泄漏
我在放置新的标准库字符串时面临内存泄漏 下面我给出了泄漏显示的代码C++ 新标准库字符串放置中的内存泄漏,c++,linux,solaris,C++,Linux,Solaris,我在放置新的标准库字符串时面临内存泄漏 下面我给出了泄漏显示的代码 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
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)
实际泄漏报告(实际泄漏:1总大小:52字节)
泄漏的分配调用堆栈总数
尺寸块
地址
========== ====== =========== =======================================
52 1 0x43f68运算符新建
这是真正的内存泄漏还是dbx将其视为泄漏?您仍然需要为通过placement new创建的字符串对象调用析构函数
std::string
为它存储在堆上的字符分配存储(除非您指定了自定义分配器,这可能是您在这里要找的),并且您正在泄漏它。(sizeof(string)
是一个常量,不取决于字符串中存储的内容。)您是否在任何地方调用\u string
的std::string
析构函数?您试图实现什么?也就是说,你为什么要使用新的布局?使用这个坏的解决方案,您试图解决的原始问题是什么(我的意思是,新的解决方案是坏的,除非您的代码在没有真正内存管理的环境中执行)请注意,您的\u string
数组不能保证与std::string
适当对齐。挑剔:您需要显式调用通过placementnew
创建的所有对象的析构函数。示例:name.~string()代码>。您好,非常感谢您的回答。我以前尝试过以_string->~string()的形式调用析构函数,它会导致编译错误,并且会出错,我不知道在这种情况下是否应该调用STL::析构函数。现在我只是尝试将类型转换为字符串并调用析构函数。现在它没有泄露任何信息。((string*)\u string)->~string()@user1357856:这是正确的做法,但更正确的做法是不要使用placement new。在这种情况下,它不会给您带来任何好处(除了调用析构函数的语法有点疯狂)。字符串“contents”仍然与堆上的new
一起分配,与那里的代码一起分配,因此据我所知,它没有做任何有用的事情。