2

我在放置新的标准库字符串时面临内存泄漏。

下面我给出了泄漏显示的代码。

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 将其解释为泄漏?

4

1 回答 1

6

您仍然需要为您通过放置 new 创建的字符串对象调用析构函数。

std::string为其存储在堆上的字符分配存储空间(除非您指定自定义分配器,这可能是您在此处所追求的),并且您正在泄漏它。(sizeof(string)是一个常数,不依赖于存储在字符串中的内容。)

于 2012-04-27T07:29:07.753 回答