delete()
ตัวดำเนินการ delete ใช้ปล่อยหน่วยความจำที่จองด้วย new รูปแบบการใช้งาน:
delete pointer_variable;
สำหรับอาเรย์:
delete[] pointer_variable;
ตัวอย่าง 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;
}
free()
ฟังก์ชัน free() ใช้ปล่อยหน่วยความจำที่จองด้วย malloc() ไม่เปลี่ยนค่าของพอยน์เตอร์ (ยังชี้ไปที่ตำแหน่งเดิม) รูปแบบ:
void free(void *pointer_name);
ตัวอย่าง free
#include <stdio.h>
#include <stdlib.h>
int main() {
int n = 4, i, *p, s = 0;
p = (int*) malloc(n * sizeof(int));
if(p == NULL) {
printf("\nError! memory not allocated.");
exit(0);
}
printf("\nEnter elements of array : ");
for(i = 0; i < n; ++i) {
scanf("%d", p + i);
s += *(p + i);
}
printf("\nSum : %d", s);
free(p);
return 0;
}
สรุปความแตกต่าง
new/delete− ใช้ใน C++ เรียก Constructor/Destructor จัดการหน่วยความจำอัตโนมัติmalloc/free− ใช้ใน C จอง/ปล่อยหน่วยความจำดิบ ไม่เรียก Constructor/Destructor