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;

更新於:26-Jun-2020

380 Views

開啟您的 事業

透過完成課程獲得認證

開始吧
廣告資訊
© . All rights reserved.