问题
I have my custom class, like:
class MyClass {
public:
int i;
std:string name;
void DoSomeStuff();
}
and another class with a list of my custom class:
class MyClassList {
public:
std::vector<MyClasss> myClassList;
}
How shall be the list destructor in order to release all used vector space in memory:
MyClassList::~MyClassList
{
myClassList.clear();
delete &myClassList;
}
Is that code right, redundant or wrong ?
Thanks for helping...
回答1:
You don't need to do anything, just let it fall out of scope. RAII will ensure that the vector memory is cleaned up when your instance of MyClassList
falls out of scope.
回答2:
This code is redundant (and as Cyber pointed out even incorrect because you are not allowed to delete
the vector).
Note that you can and must delete
only things allocated with new
and that exactly once. Same applies to new[]
and delete[]
. Having a member that must be deleted would be a case where your own destructor would make sense, although leaving resource handling to resource handlers like smart pointers and std::vector
is usually the way to go.
The implicitly generated destructor will destruct all members and bases in reverse order of construction, i.e. it will call all their destructors in the right order. So the destructor of std::vector
will be called and release all resources it owns.
This principle applies to all well-designed classes and is known as RAII.
回答3:
Since everything is created on the stack, once the object you instantiate from your List class leaves scope its implicit destructor will call std::vector's destructor for you. If you want to make sure you can have your own destructor and use your member variables vector's.clear() to clear out its contents. The only time you need delete is when you are creating new memory on the heap! However I would not use new and delete unless if the new and delete calls are in your classes private methods and are both in the same method or if new is in the constructor and delete is in the destructor. Even then, it is still better to use shared_ptr<> and unique_ptr<> for if you do not use their release methods their destructors will do it for you automatically when the objects lose scope preventing memory leaks !
来源:https://stackoverflow.com/questions/29927429/c-correct-way-to-free-a-vector-of-a-custom-class