dfine
dfine

Reputation: 11

memory leak in C++ class

I've defined two classes CA and 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). mpz_t is a GMP datatype. 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 () {
???
}

Upvotes: 1

Views: 116

Answers (1)

Kostas
Kostas

Reputation: 4186

You can use std::unique_ptr instead of a regular pointer. 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 [].

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

Upvotes: 3

Related Questions