C++ 中的 delete 操作符
delete 运算符用于释放内存。用户有权限使用此 delete 运算符释放创建的指针变量。
以下是 C++ 语言中 delete 运算符的语法:
delete pointer_variable;
以下是删除已分配内存块的语法:
delete[ ] pointer_variable;
以下是 C++ 语言中 delete 运算符的一个示例:
示例
#include <iostream> using namespace std; int main () { int *ptr1 = NULL; ptr1 = new int; float *ptr2 = new float(299.121); int *ptr3 = new int[28]; *ptr1 = 28; cout << "Value of pointer variable 1 : " << *ptr1 << endl; cout << "Value of pointer variable 2 : " << *ptr2 << endl; if (!ptr3) cout << "Allocation of memory failed\n"; else { for (int i = 10; i < 15; i++) ptr3[i] = i+1; cout << "Value of store in block of memory: "; for (int i = 10; i < 15; i++) cout << ptr3[i] << " "; } delete ptr1; delete ptr2; delete[] ptr3; return 0; }
输出
Value of pointer variable 1 : 28 Value of pointer variable 2 : 299.121 Value of store in block of memory: 11 12 13 14 15
在上述程序中,声明了四个变量,其中一个是存储由 malloc 分配的内存的指针变量 *p。数组的元素由用户打印,并且打印元素的总和。要删除那些已分配的内存,请使用 delete ptr1、delete pt2 和 delete[] ptr3。
int *ptr1 = NULL; ptr1 = new int; float *ptr2 = new float(299.121); int *ptr3 = new int[28]; *ptr1 = 28; cout << "Value of pointer variable 1 : " << *ptr1 << endl; cout << "Value of pointer variable 2 : " << *ptr2 << endl; if (!ptr3) cout << "Allocation of memory failed\n"; else { for (int i = 10; i < 15; i++) ptr3[i] = i+1; cout << "Value of store in block of memory: "; for (int i = 10; i < 15; i++) cout << ptr3[i] << " "; } delete ptr1; delete ptr2; delete[] ptr3;
广告信息