Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will deleting a structure's pointer also delete pointers within the structure?

Assume I have a structure with two pointers each pointing to an object that has an implemented destructor. Also assume that the head points to a Listnode structure that has a non-NULL value *student and *next:

struct Listnode {    
  Student *student;
  Listnode *next;
};
Listnode *head =  new Listnode;

If I use the delete reserve word on the Listnode pointer 'head' will it call the destructors within that structures Student class and Listnode class which 'student' and 'next' point-to respectively. In other words, will deleting *head also delete *student and *next provided head was the only pointer to that Listnode

like image 375
Pat Murray Avatar asked Apr 10 '12 00:04

Pat Murray


People also ask

What happens when you delete a pointer to a pointer?

The address of the pointer does not change after you perform delete on it. The space allocated to the pointer variable itself remains in place until your program releases it (which it might never do, e.g. when the pointer is in the static storage area).

Does deleting a pointer delete the object?

Pointer to object is not destroyed, value or memory block pointed by pointer is destroyed.

What happens if you delete a pointer twice?

If delete is applied to one of the pointers, then the object's memory is returned to the free store. If we subsequently delete the second pointer, then the free store may be corrupted.

What happens when you delete a pointer C++?

It destroys the memory at the runtime. It should only be used either for the pointers pointing to the memory allocated using the new operator or for a NULL pointer.


2 Answers

Not unless your destructor ~Listnode calls delete on the pointers. Calling delete will, however, invoke the destructors of non-pointer members.

like image 90
Sergey Kalinichenko Avatar answered Sep 28 '22 09:09

Sergey Kalinichenko


No!you should delete them manually first, but you could also add the delete codes in the destructor method.

like image 30
cloudygoose Avatar answered Sep 28 '22 07:09

cloudygoose