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?
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.
The rule of thumb is every new must have a corresponding delete .
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With