You seem a little confused. There are two concepts here:
- How do I, the owner of
tmp , free objects referenced within tmp ? - What should the destructor do for the class
object ( ~object )?
This is actually not the case. When you are done with the tmp vector, you must manually go through and call delete for each of your elements to free the memory occupied by the object pointed to by the element. This suggests that the elements were highlighted using new , of course.
The purpose of the object ~object descriptor is to free everything that belongs to the object , rather than free the object . If the object object does not have any dynamically allocated data, it does not need to do anything.
In other words, when you write delete tmp[i] , two things happen:
*(tmp[i])::~object() is called- The memory pointed to by
tmp[i] is freed.
Note that (2) happens even if (1) does absolutely nothing. The step (1) should allow the object to be freed in order to free any of its member objects that need to be freed. The task of the destructor does not decisively release the object on which it was called.
As an explicit example:
class object { private: int foo; public: object() : foo(42) {} ~object() { } }; int main() { vector<object*> tmp; tmp.push_back(new object());
Or vice versa,
class object { private: int* foo; public: object() : foo(new int()) { *foo = 42; } ~object() {
source share