Consider the following code:
#include "iostream" #include "conio.h" using namespace std; class sample { private: int i; public: sample(int ii=0) : i(ii){ cout<<"Constructing Object"<<endl; } ~sample() { cout<<"Destructing Object"<<endl; } void* operator new(size_t nSize, void* loc){ cout <<"Inside new"<<endl; cout <<loc<<endl; return loc; } void operator delete(void* ptr){ cout <<"Inside delete"<<endl; free(ptr); } }; int main() { int intArr[2]; sample* samplePtr = new(intArr) sample(5); cout <<samplePtr<<endl; delete samplePtr; // samplePtr->sample::~sample(); getch(); }
Output:
Inside New 0x22ff38 Constructing Object 0x22ff38 Destructing Object Inside Delete
Here I am dynamically requesting memory that is already allocated on the stack. I read that I need to call the destructor explicitly as soon as I finish. But when I try to call delete on the memory allocated on the stack, I get a call to the destructor. Does this mean that the memory on the stack is freed up after the destructor is called?
If I dynamically request memory allocated earlier on the heap, then I need to call delete, but is it really possible to delete free memory on the stack?
source share