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?
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.
As for vector, but for map...
for (map<int, X*>::iterator it = m.begin(); it != m.end(); ++it)
delete it->second;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With