[ACCEPTED]-Destructors and maps-destructor
Accepted answer
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.
As for vector, but for map...
for (map<int, X*>::iterator it = m.begin(); it != m.end(); ++it)
delete it->second;
0
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.
Source:
stackoverflow.com
More Related questions
Cookie Warning
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.