[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 {
        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;


Score: 1


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