I have a problem. I have encountered a data member whose destructor does not get called on going out of scope. I have tested to make sure that it is out of scope, by trying to access it (outside of the scope) but the compiler won't let me. But nevertheless the destructor is never called. Why?
void discard(){
if (it != NULL)
{
cout << "!!!!!!!!!!!!!!!!!!!\n";
node<objT> * t; node<int> abc; //abc.~node(); //compiler will let me
t = new node<objT>;
t = it -> next;
it = t;
head = it;
//t.~node(); //compiler won't let me
}
//cout << "t -> data = " << t -> data << endl; //compiler won't let me
exit (75);
return;
}
although t goes out of scope its destructor isn't called. However abc's destructor is called. Is that because t is a pointer and abc isn't?
tThe object t points to is dynamically allocated, so the destructor won't be called until you call delete on it. What you have up there is a memory leak.
t is destroyed when it goes out of scope, but it's just a pointer. What it points to is not destroyed. To do that, you need to use the delete operator.
And you never call the destructor directly (when you do, you'd know exactly why).
Either you have an automatic object - then it will be destroyed automatically when it goes out of scope or you have a dynamically allocated object, then you need to use delete on its address.
do I need to call delete on every node pointed to by -> next? or can I just call delete next?
Like I said, it's better to work through the chapter again before continuing.
Pointers are a rather simple concept, but it's important to get to the point where you "get" it.
That depends on whether the node destructor deletes next. If not, how could it suffice?
wtf wrote:
and do I also have to delete nodes that are assigned to other nodes that were created with new?
You need to understand that pointers are normal variables that store addresses. new creates an object of the desired type and returns a pointer (=an address) to it. delete takes an address to an object and destroys it. Destroying means calling the destructor and freeing the allocated memory.