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++。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。