Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Destructors and maps

Tags:

c++

destructor

class X;

class Y {
    public:
        ~Y();
    private:
        map<int,X*> m;
        vector<X*> v;
        X* px;
};

I guess the destructor for class Y should look something like this?

Y::~Y() {
    delete px; 
    for (vector<X*>::iterator it = v.begin(); it!=v.end(); it++) 
    delete *it;
    v.clear();
}

But what about Y::m?

like image 781
scarably Avatar asked Oct 21 '25 16:10

scarably


2 Answers

Nope, that's completely wrong. You have manually deleted your resources instead of using a resource managing class. This is a very bad error. You really want unique_ptr<X> or shared_ptr<X> or some similar class, instead of X*, if you are responsible for freeing them.

class Y {
    private:
        map<int,std::unique_ptr<X>> m;
        vector<std::unique_ptr<X>> v;
        std::unique_ptr<X> px;
};

Now no custom destructor required.

like image 77
Puppy Avatar answered Oct 24 '25 23:10

Puppy


As for vector, but for map...

for (map<int, X*>::iterator it = m.begin(); it != m.end(); ++it)
   delete it->second;
like image 24
ForEveR Avatar answered Oct 24 '25 22:10

ForEveR