尽管 delete 和 free() 在编程语言中具有相似的功能,但它们并不相同。在 C++ 中,delete 运算符只能用于指向使用 new 运算符分配的内存或 NULL 指针的指针,而 free() 函数只能用于指向使用 malloc() 函数分配的内存或 NULL 指针的指针。在本教程中,让我们学习 C++ 中 **free** 函数和 **delete** 运算符之间的主要区别。
free 函数的主要功能是释放运行时分配的内存。C 和 C++ 编程语言都支持使用 free() 函数。
它释放由 **calloc**、**realloc** 和 **calloc** 方法创建的动态分配内存,并为将来使用提供额外的可重用堆内存。它使用已释放指针的内存作为参数。
C++ 使用 free() 函数动态地解除分配内存。它本质上是一个 C++ 库函数,定义在头文件 stdlib.h 中。此库函数主要用于指针为 Null 或指向使用 **malloc()** 函数或 Null 指针分配的内存时。
语法
假设我们声明了一个名为“ptr”的指针,现在我们希望解除分配其内存
free(ptr);
前面的语法将释放分配给指针变量 'ptr' 的内存
Ptr 是上面提到的语法中 free() 方法内部的一个参数。malloc()、calloc() 或 realloc 函数用于分配内存,ptr 是指向该内存块的指针。此指针也可能为 null,或者已使用 malloc 分配但未指向任何其他内存块。
free() 函数无法执行任何操作。free() 函数不返回任何值。其主要目的是释放内存。
free() 函数如何与 malloc() 配合使用?
让我们看一个例子。
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
int *ptr;
ptr = (int*) malloc(7*sizeof(int));
cout << "Please enter 7 integer" << endl;
for (int i=0; i<7; i++)
{
// *(ptr+i) can be replaced by ptr[i]
cin >>ptr[i];
}
cout << endl << " entered value"<< endl;
for (int i=0; i<7; i++)
{
cout <<*(ptr+i) << " ";
}
free(ptr);
/* prints a garbage value just after the ptr is free */
cout << "Garbage Value" << endl;
for (int i=0; i<7; i++)
{
cout << *(ptr+i)<< " ";
}
return 0;
}
输出
Please enter 7 integer 1 2 3 4 5 6 7 entered value 1 2 3 4 5 6 7 Garbage Value 0 0 3 4 5 6 7
前面的代码演示了 free() 函数如何与 malloc() 配合使用。我们首先声明整数指针 *ptr,然后使用 malloc() 函数为该指针变量分配内存。Ptr 现在指向一个包含七个整数的未初始化内存块。使用 free() 函数,我们可以在使用后删除已分配的内存。当我们尝试打印 ptr 指向的值时,会返回一个垃圾值,表示内存已被解除分配。
让我们看一个例子。
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
float *ptr; //declaration of float pointer
ptr=(float*)calloc(1,sizeof(float));
*ptr=8.7;
std::cout << " Value of *ptr just before applying free() function : " <<*ptr<< std::endl;
free(ptr);
std::cout << " Value of *ptr just after applying free() function :" <<*ptr<< std::endl;
return 0;
}
输出
Value of *ptr just before applying free() function : 8.7 Value of *ptr just after applying free() function :0
从上面的示例中可以看出,free() 函数使用 calloc()。使用 calloc() 函数将内存块分配给 float 指针 ptr。ptr 已被赋予一个可以存储单个浮点类型值的内存块。
delete 运算符执行与 free 函数相同的任务,主要用于释放运行时分配的内存。C++ 编程中通常使用 delete 运算符。
它是一种运算符,用于释放由 new 关键字(如对象和数组)分配的内存。当 delete 函数与 C++ 中的对象一起使用时,它首先执行对象的析构函数,然后才释放它正在使用的内存。有关 C++ 中 delete 运算符的详细解释,请查看 C++ 内存管理教程。
语法
delete obj;
| 基于 | Free | Delete |
|---|---|---|
| 理想用途 | 使用 malloc、calloc 和 realloc 函数解除分配已占用的内存。 | 释放通过 new 关键字分配的内存。 |
| 指代 | Free 函数主要指库函数。 | 它指运算符 |
| 重载 | 不可能 | 可能 |
| 执行速度 | 慢 | 快 |
stdlib.h 头文件中的一个库函数。free() 函数较慢,因为我们都知道它是一个需要从头文件接收其声明的函数。由于 delete 运算符是一个运算符——我们都知道运算符比函数移动得更快。