C++ delete operator
Created By: chatGPT
In C++, the
delete
operator is used to deallocate memory that was previously allocated with the new
operator. It helps prevent memory leaks by freeing up memory that is no longer needed. There are two forms: delete
for single objects and delete[]
for arrays.// Deleting a single object
int* singleInt = new int(5);
delete singleInt;
// Deleting an array of objects
int* intArray = new int[10];
delete[] intArray;
When you use
delete
, it calls the destructor for the object, ensuring that any resources it holds are released properly. It's important to avoid using delete
on pointers that have already been deleted; this leads to undefined behavior.// Using delete safely
class MyClass {
public:
MyClass() { /* Constructor code */ }
~MyClass() { /* Destructor code */ }
};
MyClass* obj = new MyClass();
delete obj; // Proper deletion
Pointer safety is critical in C++. Always set your pointer to nullptr after deletion to prevent dangling pointers, which can lead to crashes or unstable program behavior.
// Setting pointer to nullptr after deletion
int* deletedInt = new int(10);
delete deletedInt;
deletedInt = nullptr; // Safe practice