Delete operator | Sololearn: Learn to code for FREE!

+1

Delete operator

Hello Refer below code : #include <iostream> using namespace std; class Test { public: Test () {cout << "constructor" << endl;} ~Test () {cout << "destructor" << endl;} }; int main() { Test* obj = new Test(); delete obj; delete obj; delete obj; delete obj; return 0; } Can someone explain output of this ? Why it prints destructor twice even though delete is called five times... As far as I recall, I somewhere read that one can delete same memory location twice , but why? and after that, delete call for future thrice should result in memory corruption.... Any thoughts?

7/20/2018 4:38:44 PM

Ketan Lalcheta

3 Answers

New Answer

+1

Ketan Lalcheta I think that depends by compiler/system but i repeat, dont do it because standards say that result its undefined

0

Into C++ standard, a call to delete on a not-new allocated memory has undefined result (depends on multiple factors)... Then dont do it.

0

This is allocated memory by New operator.. Why it works only exactly for twice...???