I have ;
class object {
// any private datas token in heap area
public :
~object () ;
};
<
You seem to be a bit confused. There are two concepts at play here:
tmp
, deallocate the objects referred to by the pointers within tmp
?object
class (~object
) do?These are not really that related. When you are finished with the tmp
vector, you must manually go through and call delete
on each of its elements in order to deallocate the memory occupied by the object
object that the element points to. This is assuming the elements were allocated with new
, of course.
The purpose of the object
destructor ~object
is to deallocate everything that the object
object owns, not to deallocate the object
object itself. If the object
object does not own 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 calledtmp[i]
is deallocatedNote that (2) happens even if (1) does absolutely nothing. The point of step (1) is to allow the object that is about to be deallocated to deallocate any of its member objects that need to be deallocated. The destructor's job is emphatically not to deallocate the object that it was invoked on.
By way of explicit example:
class object {
private:
int foo;
public:
object() : foo(42) {}
~object() { /* nothing to do here; foo is not dynamically allocated */ }
};
int main() {
vector
Or, by contrast
class object {
private:
int* foo;
public:
object() : foo(new int()) { *foo = 42; }
~object() {
// Now since foo is dynamically allocated, the destructor
// needs to deallocate it
delete foo;
}
};
int main() {
vector