Delete是一個運算符,用於銷毀由新表達式創建的數組和非數組(指針)對象。
- 可以通過使用Delete運算符或Delete []運算符來使用Delete
- New運算符用於動態內存分配,從而將變量放在堆內存中。
- 這意味著Delete運算符從堆中釋放內存。
- 指向對象的指針不會被破壞,指針所指向的值或存儲塊將被破壞。
在以下示例中,我們可以應用刪除運算符:
1.刪除數組對象:我們使用[]括號刪除數組。
// Program to illustrate deletion of array
#include <bits/stdc++.h>
using namespace std;
int main()
{
// Allocate Heap memory
int* array = new int[10];
// Deallocate Heap memory
delete[] array;
return 0;
}
2.刪除NULL指針:刪除NULL不會導致任何更改,也不會出錯。
// C++ program to deleting
// NULLL pointer
#include <bits/stdc++.h>
using namespace std;
int main()
{
// ptr is NULL pointer
int* ptr = NULL;
// deleting ptr
delete ptr;
return 0;
}
3.刪除指針有或沒有價值
#include <bits/stdc++.h>
using namespace std;
int main()
{
// Creating int pointer
int* ptr1 = new int;
// Initializing pointer with value 20
int* ptr2 = new int(20);
cout << "Value of ptr1 = " << *ptr1 << "\n";
cout << "Value of ptr2 = " << *ptr2 << "\n";
delete ptr1; // Destroying ptr1
delete ptr2; // Detroying ptr2
return 0;
}
輸出:
Value of ptr1 = 0 Value of ptr2 = 20
4.刪除一個虛空指針
#include <bits/stdc++.h>
using namespace std;
int main()
{
void* ptr; // Creating void pointer
delete ptr; // Destroying void pointer
cout << "ptr deleted successfully";
return 0;
}
輸出:
ptr deleted successfully
5.刪除動態分配的內存分配
#include <bits/stdc++.h>
using namespace std;
int main()
{
// Dynamic memory allocated by using malloc
int* ptr2 = (int*)malloc(sizeof(int));
delete ptr2;
cout << "ptr2 deleted successfully";
return 0;
}
輸出:
ptr2 deleted successfully
盡管以上程序在GCC上運行良好。不建議對malloc()使用刪除。
6.刪除變量用戶定義的數據類型:
#include <bits/stdc++.h>
using namespace std;
struct P {
static void operator delete(void* ptr, std::size_t sz)
{
cout << "custom delete for size " << sz <<endl;
delete (ptr); //::operator delete(ptr) can also be used
}
static void operator delete[](void* ptr, std::size_t sz)
{
cout << "custom delete for size " << sz <<endl;
delete (ptr); //::operator delete(ptr) can also be used
}
};
int main()
{
P* var1 = new P;
delete var1;
P* var2 = new P[10];
delete[] var2;
}
輸出:
custom delete for size 1 custom delete for size 18
異常:
1.嘗試刪除非指針對象
#include <bits/stdc++.h>
using namespace std;
int main()
{
int x;
// Delete operator always
// requires pointer as input
delete x;
return 0;
}
輸出:
error:type ‘int’ argument given to ‘delete’, expected pointer
2.嘗試刪除指向本地堆棧分配變量的指針。
#include <bits/stdc++.h>
using namespace std;
int main()
{
int x;
int* ptr1 = &x;
// x is present on stack frame as
// local variable, only dynamically
// allocated variables can be destroyed
// using delete operator
delete ptr1;
return 0;
}
輸出:
Runtime error
注:本文由純淨天空篩選整理自Abhishek rajput大神的英文原創作品 delete() in C++。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。