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?

20th Jul 2018, 4:38 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
3 ответов
+ 1
Ketan Lalcheta I think that depends by compiler/system but i repeat, dont do it because standards say that result its undefined
21st Jul 2018, 12:23 PM
KrOW
KrOW - avatar
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.
20th Jul 2018, 5:37 PM
KrOW
KrOW - avatar
0
This is allocated memory by New operator.. Why it works only exactly for twice...???
21st Jul 2018, 11:46 AM
Ketan Lalcheta
Ketan Lalcheta - avatar