TheDocumentation Index
Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
Use this file to discover all available pages before exploring further.
delete operator is a unary operator used to deallocate memory that was previously allocated dynamically on the free store (heap) using the new operator. It destroys the object at the specified memory address and returns the memory to the system, preventing memory leaks.
Syntax
The operator has two distinct forms depending on how the memory was originally allocated:Execution Mechanics
When thedelete operator is invoked, it executes a strict two-step process:
- Destruction: It invokes the destructor of the object (or, in the case of
delete[], the destructors of every object in the array in reverse order of their construction). This allows the object to safely release any internal resources. - Deallocation: It calls the underlying memory deallocation function (
operator deleteoroperator delete[]) to return the raw memory bytes to the free store.
Technical Rules and Undefined Behavior
To maintain memory safety, thedelete operator is governed by strict rules. Violating these rules typically results in undefined behavior (UB):
- Null Pointers: Applying
deleteordelete[]to anullptris a guaranteed no-operation. It is inherently safe and requires no explicit null-check prior to invocation. - Form Matching: The scalar
deletemust strictly pair with the scalarnew. The arraydelete[]must strictly pair with the arraynew[]. Mismatching these forms (e.g., usingdeleteon a pointer allocated withnew[]) causes UB. - Double Free: Invoking
deleteon a memory address that has already been deallocated results in UB. - Non-Dynamic Memory: Applying
deleteto a pointer referencing memory not allocated bynew(such as stack-allocated variables or statically allocated memory) results in UB. - Polymorphic Deletion: If
deleteis applied to a base class pointer that points to a derived class object, the base class must have avirtualdestructor. If the base class destructor is not virtual, the invocation results in UB (typically failing to call the derived class’s destructor, resulting in resource leaks). - Incomplete Types: Applying
deleteto a pointer of an incomplete class type results in UB if the fully defined class ultimately possesses a non-trivial destructor or a class-specificoperator delete.
Dangling Pointers
After thedelete operator completes execution, the pointer variable itself continues to exist in its current scope and retains the now-invalid memory address. This is known as a dangling pointer. Dereferencing a dangling pointer results in UB.
Overloading operator delete
While the delete operator itself (the two-step process of destruction and deallocation) cannot be overloaded, the underlying deallocation function (operator delete) can be overloaded either globally or at the class scope to implement custom memory management strategies.
Master C++ with Deep Grasping Methodology!Learn More





