What exactly delete Keyword do in C++


Just think of memory as a storeroom with lots of boxes to put things into. When you call "new", the storekeeper assigns you an unused box with sufficient size to put your stuffs into it, and keep record of  box no in his diary. This number would be the "pointer". Now, when you "delete" that pointer, the reverse happens: the storekeeper notes that this particular box is available again. As storekeeper are not doing anything with the box, so if you look into it after a "delete" you might see your old stuff. Or you might see somebody else’s stuff, if the box was reassigned in the meanwhile.


#include <iostream>

int main()
{
    int* p = new int;
    *p= 100;
    std::cout << " before delete *p =" << *p <<std::endl;
    delete (p);
    std::cout << " after delete *p =" << *p <<std::endl;
    return 0;
}

Output:

before delete *p =100
after delete *p =0


...

No comments:

Post a Comment

Rendering 3D maps on the web using opesource javascript library Cesium

This is a simple 3D viewer using the Cesium javascript library. The example code can be found here . Click on question-mark symbol on upp...