STL 2D Vectors and clear()
Does this clean up properly?
std::vector< std::vector<SomePointer*> > vec;
....
SomeClass::~SomeClass
{
vec.clear();
}
Does that properly destroy all the pointers, or do I have to iterate through the 2d vector and call clear for each element?
It will destroy each of the "child" vectors, yes. Of course, it won't destroy the objects the pointers point to.
Standard library containers look after THEIR memory. Automatically. You should almost never call .clear() explicitly; certainly not in a destructor, because it does nothing - if your object is destructed, then its members are destructed, and the container's destructor has the same effect as .clear() anyway.
YOU are expected to look after your memory. In your case, that would be the SomePointer instances that all those SomePointer*'s point at.
Note that in general, you can have several SomePointer*'s pointing at the same SomePointer, and your job is to arrange for EVERY SomePointer to get deallocated EXACTLY ONCE. This means finding ONE SomePointer* that points at each, and calling delete on it. Oh, and you also have to distinguish between scalar and array allocations: a new call MUST match a delete call, and a new[] call MUST match a delete[] call.
In general, this is hellish. Which is why you simplify your design when you can, use smart pointers and smart containers when you have to, and use raw pointers when you *really, really* have to, which is *almost never* in modern C++.
YOU are expected to look after your memory. In your case, that would be the SomePointer instances that all those SomePointer*'s point at.
Note that in general, you can have several SomePointer*'s pointing at the same SomePointer, and your job is to arrange for EVERY SomePointer to get deallocated EXACTLY ONCE. This means finding ONE SomePointer* that points at each, and calling delete on it. Oh, and you also have to distinguish between scalar and array allocations: a new call MUST match a delete call, and a new[] call MUST match a delete[] call.
In general, this is hellish. Which is why you simplify your design when you can, use smart pointers and smart containers when you have to, and use raw pointers when you *really, really* have to, which is *almost never* in modern C++.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement