Computer >> Máy Tính >  >> Lập trình >> C ++

toán tử delete () trong C ++

Toán tử xóa được sử dụng để phân bổ bộ nhớ. Người dùng có đặc quyền phân bổ biến con trỏ được tạo bởi toán tử xóa này.

Đây là cú pháp của toán tử xóa trong ngôn ngữ C ++,

delete pointer_variable;

Đây là cú pháp để xóa khối bộ nhớ được cấp phát,

delete[ ] pointer_variable;

Đây là một ví dụ về toán tử xóa trong ngôn ngữ C ++,

Ví dụ

#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;
}

Đầu ra

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

Trong chương trình trên, bốn biến được khai báo và một trong số chúng là biến con trỏ * p đang lưu bộ nhớ được cấp phát bởi malloc. Các phần tử của mảng được in bởi người dùng và tổng các phần tử được in. Để xóa các bộ nhớ được cấp phát đó, sử dụng xóa ptr1, xóa pt2 và xóa [] 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;