Assume you have an object of class Fool.
class Fool
{
int a,b,c;
double* array ;
//...
~Fool()
{
// destroys the array..
delete[] array ;
}
};
Fool *fool = new Fool() ;
Now, I know you shouldn’t, but some fool calls the destructor on fool anyway. fool->~Fool();.
Does that mean fool‘s memory is freed, (ie a,b,c are invalid) or does that mean only whatever deallocations in ~Fool() function occur (ie the array is deleted only?)
So I guess my question is, is a destructor just another function that gets called when delete is called on an object, or does it do more?
If you write
You end the object’s lifetime, which invokes the destructor and reclaims the inner
arrayarray. The memory holding the object is not freed, however, which means that if you want to bring the object back to life using placement new:you can do so.
According to the spec, reading or writing the values of the fields of
foolafter you explicitly invoke the destructor results in undefined behavior because the object’s lifetime has ended, but the memory holding the object should still be allocated and you will need to free it by invokingoperator delete:The reason to use
operator deleteinstead of just writingis that the latter has undefined behavior, because
fool‘s lifetime has already ended. Using the raw deallocation routineoperator deleteensures that the memory is reclaimed without trying to do anything to end the object’s lifetime.Of course, if the memory for the object didn’t come from
new(perhaps it’s stack-allocated, or perhaps you’re using a custom allocator), then you shouldn’t useoperator deleteto free it. If you did, you’d end up with undefined behavior (again!). This seems to be a recurring theme in this question. 🙂Hope this helps!