gpt4 book ai didi

c++ - 使用 std::list 时 std::string 的内存泄漏

转载 作者:IT老高 更新时间:2023-10-28 22:06:37 24 4
gpt4 key购买 nike

我正在使用 std::list<std::string>在我目前的项目中。但是与此相关的某个地方存在内存泄漏。所以我单独测试了有问题的代码:

#include <iostream>
#include <string>
#include <list>

class Line {
public:
Line();
~Line();
std::string* mString;
};

Line::Line() {
mString = new std::string("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
}

Line::~Line() {
//mString->clear(); // should not be neccessary
delete mString;
}

int main(int argc, char** argv)
{
// no memory leak
while (1==1) {
std::string *test = new std::string("XXXXXXXXXXXXXXXXXXXXXXXX");
delete test;
}

// LEAK!
// This causes a memory overflow, because the string thats added
// to the list is not deleted when the list is deleted.
while (1==1) {
std::list<std::string> *sl = new std::list<std::string>;
std::string *s = new std::string("XXXXXXXXXXXXXXXXXXXXXXX");
sl->push_back(*s);
//sl->pop_back(); //doesn't delete the string?- just the pointer
delete sl;
}

// LEAK!
// Here the string IS deleted, but the memory does still fill up
// but slower
while (1==1) {
std::list<Line> *sl = new std::list<Line>;
Line *s = new Line();
sl->push_back(*s);
//sl->pop_back(); //does delete the Line-Element
sl->clear();
delete sl;
}
return 0;

// this does not cause any noticable memory leak
while (1==1) {
std::list<int> *sl = new std::list<int>;
int i = 0xFFFF;
sl->push_back(i);
sl->clear();
delete sl;
}
return 0;

// This does not cause any overflow or leak
while (1==1) {
int *i;
i= new int [9999];
delete[] i;
}

}

为什么我的字符串列表会导致内存泄漏?删除列表不应该导致在每个包含的字符串上调用析构函数吗?

最佳答案

在第一种情况下,list class 不知道您使用 new 分配了字符串,并且无法删除它。特别是,该列表只包含您传入的字符串的拷贝。

同样,在第二种情况下,您永远不会释放行对象 s,因此会泄漏内存。删除内部字符串的原因是您没有正确实现复制构造函数。因此,如果你复制一个 Line 对象,它们都会引用同一个字符串指针,如果你试图删除它们,你就有麻烦了。

关于c++ - 使用 std::list<std::string> 时 std::string 的内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3428750/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com