C++ 中的 delete 和 free()
delete和free()在编程语言中具有相似的功能,但它们是不同的。在 C++ 中,delete运算符只能用于指向使用 new运算符分配的内存的指针或 NULL 指针,free() 只能用于指向使用 malloc() 分配的内存的指针或对于 NULL 指针。
delete 和 free 的区别在于: delete() free()It is an operator. It is a library function. It de-allocates the memory dynamically. It destroys the memory at the runtime. It should only be used either for the pointers pointing to the memory allocated using the new operator or for a NULL pointer. It should only be used either for the pointers pointing to the memory allocated using malloc() or for a NULL pointer. This operator calls the destructor after it destroys the allocated memory. This function only frees the memory from the heap. It does not call the destructor. It is faster. It is comparatively slower than delete as it is a function.
Note: The most important reason why free() should not be used for de-allocating memory allocated using new is that, it does not call the destructor of that object while delete operator does.
删除运算符示例:
CPP
// CPP program to demonstrate the correct and incorrect
// usage of delete operator
#include
#include
using namespace std;
// Driver Code
int main()
{
int x;
int* ptr1 = &x;
int* ptr2 = (int*)malloc(sizeof(int));
int* ptr3 = new int;
int* ptr4 = NULL;
// delete Should NOT be used like below because x is
// allocated on stack frame
delete ptr1;
// delete Should NOT be used like below because x is
// allocated using malloc()
delete ptr2;
// Correct uses of delete
delete ptr3;
delete ptr4;
getchar();
return 0;
}
C++
// CPP program to demonstrate the correct and incorrect
// usage of free() function
#include
#include
using namespace std;
// Driver Code
int main()
{
int* ptr1 = NULL;
int* ptr2;
int x = 5;
ptr2 = &x;
int* ptr3 = (int*)malloc(5 * sizeof(int));
// Correct uses of free()
free(ptr1);
free(ptr3);
// Incorrect use of free()
free(ptr2);
return 0;
}
free()函数示例:
C++
// CPP program to demonstrate the correct and incorrect
// usage of free() function
#include
#include
using namespace std;
// Driver Code
int main()
{
int* ptr1 = NULL;
int* ptr2;
int x = 5;
ptr2 = &x;
int* ptr3 = (int*)malloc(5 * sizeof(int));
// Correct uses of free()
free(ptr1);
free(ptr3);
// Incorrect use of free()
free(ptr2);
return 0;
}