gpt4 book ai didi

c++ - 指向具有 vector 内存泄漏的对象的指针

转载 作者:行者123 更新时间:2023-11-28 03:19:03 25 4
gpt4 key购买 nike

我似乎对 vector 有一点内存泄漏问题。我的代码如下所示:

    class CPart {
public:
virtual void print() = 0;
};

//some other classes

class CDisk : public CPart {
public:
CDisk(int tp, int size);
~CDisk();
virtual void print();
void AddPartition(int size, const string & dsc);

static const int MAGNETIC = 0;
static const int SDD = 1;
private:

struct CPartition {
CPartition(int size, const string & dsc);
int div_size;
string disk;
};
int type;
int d_size;
vector<CPartition> ptts;
};

CDisk::CDisk(int tp, int size) {
type = tp;
d_size = size;
}

CDisk::CPartition::CPartition(int size, const string& dsc) {
div_size = size;
disk = dsc;
}

void CDisk::AddPartition(int size, const string& dsc) {
ptts.push_back(CPartition(size, dsc));
}

int main(int argc, char** argv) {
CDisk disk(CDisk::SDD, 5000);
disk.AddPartition(500, "disk1");
CPart *disk2 = new CDisk(disk);
delete disk2;
return 0;
}

当我用 valgrind 运行这段代码时,它说存在内存泄漏,丢失的字节数等于 vector ptts 中的项目数 * CPartition 的大小。所以我猜我必须以某种方式清理那个 vector 。我已经尝试过了,但无济于事。

最佳答案

你需要有 virutal destructor在C部分

 class CPart {
public:
virtual void print() = 0;
virtual ~CPart(){};
};

否则会出现以下情况;

  int main(int argc, char** argv) {
CDisk disk(CDisk::SDD, 5000);
disk.AddPartition(500, "disk1");
CPart *disk2 = new CDisk(disk);//CDisk created
delete disk2;//But here only CPart is deleted leaving CDisks data in memory
return 0;
}

关于c++ - 指向具有 vector 内存泄漏的对象的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15997807/

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