How is the delete keyword used in C++?
In C++, the delete keyword is used to release dynamically allocated memory and destroy objects. It has two main purposes:
- brand new
- remove
int* ptr = new int; // 动态分配一个整数的内存
// 使用ptr
delete ptr; // 释放内存
- fresh
- remove
MyClass* obj = new MyClass; // 动态创建一个MyClass对象
// 使用obj
delete obj; // 销毁对象并释放内存
It is important to note that when using the delete operator to free memory, it must be ensured that the memory being released was dynamically allocated using the new operator. Otherwise, the behavior is undefined. Furthermore, it is important to avoid releasing the same block of memory multiple times, as this can also lead to undefined behavior.