ในบทช่วยสอนนี้ เราจะพูดถึงโปรแกรมเพื่อทำความเข้าใจฟังก์ชัน delete() และ free() ใน C++
ฟังก์ชันทั้งสองนี้ใช้เพื่อจุดประสงค์เดียวกันเป็นหลัก เช่น การเพิ่มหน่วยความจำที่ไม่ได้ใช้ ตัวดำเนินการ delete() มีไว้สำหรับตัวที่จัดสรรโดยใช้ new() andfree() สำหรับผู้ที่จัดสรรโดยใช้ malloc()
ตัวอย่าง
#include<stdio.h>
#include<stdlib.h>
int main(){
int x;
int *ptr1 = &x;
int *ptr2 = (int *)malloc(sizeof(int));
int *ptr3 = new int;
int *ptr4 = NULL;
//incorrect usage of delete
delete ptr1;
delete ptr2;
//correct usage of delete
delete ptr3;
delete ptr4;
getchar();
return 0;
}