Destructor

Aug 8, 2015 at 1:30pm
I know that the destructor is used to free the dynamically allocated memory. Is it also correct to say that the destructor is used for destroying an object?

Aug 8, 2015 at 1:34pm
If you write a class within an instance of which you allocate memory on the heap, then it is the responsibility of that class to clear the allocated memory before its instance goes out of scope. This is done in its destructor.
Aug 8, 2015 at 1:49pm
Thanks you for the answer but my question was
Is it correct to say that the destructor is used for destroying an object?
Aug 8, 2015 at 2:06pm
Yes it correct. This is the exact wording used by the C++ standard:

The C++11 standard (§12.4/2)
A destructor is used to destroy objects of its class type.
Last edited on Aug 8, 2015 at 2:07pm
Aug 8, 2015 at 2:16pm
it is the responsibility of that class to clear the allocated memory before its instance goes out of scope. This is done in its destructor.
I want to chime in and say that it is incorrect. Destructor does not frees the memory, it just destroys object. Memory is still here and you can reuse it (if memory itself is not deleted, say, by delete operator). It cannot possibly know how to actually release memory (delete? free? some allocator-specific method?) as method to do so is not stored in class.
Aug 10, 2015 at 10:31am

I want to chime in and say that it is incorrect. Destructor does not frees the memory, it just destroys object. Memory is still here and you can reuse it (if memory itself is not deleted, say, by delete operator). It cannot possibly know how to actually release memory (delete? free? some allocator-specific method?) as method to do so is not stored in class.


Thanks for your input, obviously you need to write the code in the destructor to delete the allocated memory etc, I didn't mean that the destructor will just do it for you!
Topic archived. No new replies allowed.