I was wondering if the call to operator delete
is synchronous or not. In other words, if I do:
delete p;
Does the C++ Standard guarantee that only after this call finishes execution the memory is freed? Or is the call asynchronous and simply schedules a task for OS to free this memory as soon as it decides that it is the best time to do so?
If the first case is the valid one, then does it mean that we have to implement our own asynchronous deleter facility? I'm asking because I'd say that most of the time we (programmers) don't care when the memory is freed exactly, and therefore we don't want our code to freeze and wait for this (most likely expensive?) system call to finish, but rather schedule a task for deletion and immediately continue the execution. Does C++ provide any standard facility (maybe through standard library?) to do this without reinventing the wheel?
operator delete, operator delete[] Deallocates storage previously allocated by a matching operator new. These deallocation functions are called by delete-expressions and by new-expressions to deallocate memory after destructing (or failing to construct) objects with dynamic storage duration.
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.
Overloading New and Delete operator in c++ The new and delete operators can also be overloaded like other operators in C++. New and Delete operators can be overloaded globally or they can be overloaded for specific classes.
delete
is synchronous. Now, that doesn’t mean that the underlying memory is actually freed at that time by the operating system but from the view of the C++ system it behaves as if.
I'm asking because I'd say that most of the time we (programmers) don't care when the memory is freed exactly
But delete
isn’t mainly about memory, it’s just as much about calling a destructor in a deterministic fashion – it’s a general-purpose resource-freeing mechanism, not restricted to memory. And here it is important to have synchronicity, otherwise one of the core aspects of C++ – RAII – wouldn’t work.
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