So I'll try to be as clear as possible about this. Say we have the following:
class X : protected vector<objectY*>
{
private:
objectZ** array;
unsigned size;
unsigned capacity;
public:
X():size(0), capacity(0), array(new objectZ*[100]){}
X(const objectX& o); // to be defined later
X& operator=(const X& x); //defined later
~X(){ delete [] array; clear(); } <--- is this correct, or it produces memory leak?
void add(objectZ* o); // used to add objects to array
}
Now let's say we already defined class Y and Z with all the basic stuff we need for the above code to compile. My question is the following: Is the destructor correct? Does my code have memory leak?
Say I go to main() and I do this:
objectZ* o1 = new objectZ();
objectX* x1 = new objectX();
x1->add(o1);
delete o1; // to avoid memory leak;
return 0; // end of main.
Since I'm mostly adding stuff to objectX's array from main, and most likely using polymorphism, like
objectZ* ok = new objectK(); // where k is derived from Z
x1->add(ok);
how do I define properly the destructor of class X without having memory leaks, and considering it also inherits from a vector of pointers to another objectY, do I need to cycle the vector 1 by 1 element and call delete on it, and clear() at the end or is clear() enough? Do i cycle array and call delete on it's elements too? My thoughts are that since I'm not allocating memory from within class X, I don't need to deallocate it either. I only need to delete [] array, and possibly clear() the inherited vector.
Aucun commentaire:
Enregistrer un commentaire