📜  C++中的delete和free()

📅  最后修改于: 2021-05-30 10:56:31             🧑  作者: Mango

在C++中,delete运算符应仅用于指向使用new运算符分配的内存的指针或NULL指针,而free()则仅应用于指向使用malloc()分配的内存的指针或空指针。

为什么不应该使用free()来取消分配使用NEW分配的内存,最重要的原因是,它不调用该对象的析构函数,而删除运算符则调用该对象的析构函数。

CPP
#include
#include
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++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”