Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If I never call "new," do I ever have to call "delete"?

If I manage to construct objects in C++ by doing

Object o;

instead of

Object *o = new Object();

in every case, do I ever need to call delete or will all memory be managed automatically?

like image 246
Jeffrey Avatar asked Aug 27 '12 01:08

Jeffrey


People also ask

Do I need to call delete in C++?

It is important to explicitly call delete because you may have some code in the destructor that you want to execute. Like maybe writing some data to a log file. If you let the OS free your memory for you, your code in your destructor will not be executed.

Does New Need delete?

The rule of thumb is every new must have a corresponding delete .

When should you call delete in C++?

When delete is used to deallocate memory for a C++ class object, the object's destructor is called before the object's memory is deallocated (if the object has a destructor). If the operand to the delete operator is a modifiable l-value, its value is undefined after the object is deleted.


1 Answers

No. That object is allocated on the stack, and will be destroyed automatically when it goes out of scope. That includes freeing its memory and calling the destructor.

like image 199
mfontanini Avatar answered Sep 27 '22 19:09

mfontanini