This is an old article written in 2013, put on Gegahost.net http://raison.gegahost.net/?p=21
February, 2013How ' delete ' works? Filed under:c++-tags:c++ Delete, C + + destructor, C + + internals, C + + Virtual-raison @ 2:09 am
(Original works by Peixu Zhu)
1. Case of class without virtual destructor.
- Calling Desctructors from child to parent as a chain, which destructor to call are determined at compiling time according t o The type of the instance.
- Call "free" function to the memory, given the address of the instance.
2. Case of class with virtual destructor.
- Check the virtual pointer table, and call the destructor in table. When the destructor finish working, it'll replace the virtual pointer table with it's parent ' s virtual pointer table, an D then calling it ' s parent's desctructor like a chain.
- After chained calling of Desctructors, call "free" function to free the allocated memory, given the address of in Stance minus sizeof (void*).
3. Case of arrayed instances without virtual destructor.
- Check address of First instance minus sizeof (void*), to get the count of cells/instances, (i.e., ' n ').
- Call each instance ' s destructor, from n-1 to 0.
- Call "free" function to free the allocated memory, given the address of the first instance minus sizeof (void*).
4. Case of arrayed instances with virtual destructor.
- Check address of First instance minus sizeof (void*), to get the count of cells/instances, (i.e., ' n ').
- Call each instance ' s chained destructor, from n-1 to 0.
- Call "free" function to free the allocated memory, given the address of the first instance minus sizeof (void*).
5. Calling virtual Desctructors.
After finish working code in the destructor function, if there ' s parent class, and the parent class have virtual destructor , set the virtual pointer table to is the virtual pointer table of the parent class, then call the parent class ' s destructor r Ecursively like a chain. This was a must, because virtual methods called in virtual parent desctrutor should was the version in the parent class.
How ' delete ' works?