[ACCEPTED]-Destructors and maps-destructor

Accepted answer
Score: 21

Nope, that's completely wrong. You have 6 manually deleted your resources instead 5 of using a resource managing class. This 4 is a very bad error. You really want unique_ptr<X> or 3 shared_ptr<X> or some similar class, instead of X*, if 2 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 1 no custom destructor required.

Score: 6

As for vector, but for map...

for (map<int, X*>::iterator it = m.begin(); it != m.end(); ++it)
   delete it->second;

0

Score: 1

Same:

for (map<int,X*>::iterator it = m.begin() ; it != m.end() ; it++ )
   delete it->second;

In C++11 you can use auto to skip the iterator 2 type.

There's also no need to call v.clear(); in the 1 destructor.

More Related questions