简体   繁体   English

C ++类中的内存泄漏

[英]memory leak in C++ class

I've defined two classes CA and CB. 我已经定义了两个CA和CB类。 I would like to prevent memory leak and I don't know how to properly destroy the class CB (assuming that the memory leak is coming from it). 我想防止内存泄漏,我不知道如何正确销毁类CB(假设内存泄漏来自它)。 mpz_t is a GMP datatype. mpz_t是GMP数据类型。 Here's my code 这是我的代码

class CA {
public:
void SetFoo (unsigned long int);
CA  ();
CA  (unsigned long int);
~CA ();
private:
mpz_t foo;
};

where 哪里

CA::CA () {
mpz_init (foo);
}

CA::CA (unsigned long int in) {
mpz_init   (foo);
mpz_set_ui (foo, in);
}

CA::~CA () {
mpz_clear (foo);
}

void CA::SetFoo (unsigned long int in) {
mpz_set_ui (foo, in);
}

and

class CB {
public:
CB  ();
~CB ();
private:
list <pair<uint16_t, CA*>> mylist;
};

where 哪里

CB::CB () {
pair<uint16_t, CA*> mypair;
CA* C = new CA [2];
C [0].SetFoo (100);
C [1].SetFoo (200);
mypair.first  = 0;
mypair.second = &C[0];
mylist.push_front (mypair);
mypair.first  = 1;
mypair.second = &C[1];
mylist.push_front (mypair);
}

CB::~CB () {
???
}

You can use std::unique_ptr instead of a regular pointer. 您可以使用std::unique_ptr而不是常规指针。 This will automatically deallocate the memory on the destruction of each element. 这将在每个元素的销毁时自动释放内存。

typedef std::unique_ptr<Ca[]> CA_array;
list <pair <uint16_t, CA_array> > mylist;

Alternatively, you could iterate through the elements and deallocate memory using delete [] . 或者,您可以使用delete []遍历元素并释放内存。

CB::~CB () {
    for (auto &item : mylist) 
        delete [] item.second;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM