c++中的new和delete

来源:互联网 发布:安卓微信数据迁移 编辑:程序博客网 时间:2024/05/16 19:14

c++为程序员在堆上分配空间时提供了这两个关键字,那么这两个关键字与c语言中的malloc和free有什么区别呢?其实从低层的角度讲,这两个函数没有什么区别。都会最终去调用kernel库中的headAloc函数和headfree函数。


让我们来看一个小的例子

#include <iostream>using namespace std;class test{public:test();test(int a,int b);~test();private:int a;int b;};test::test(){this->a = 0;this->b = 0;cout<<"test()"<<endl;}test::test(int a,int b){this->a = a;this->b = b;cout<<"test(int,int)"<<endl;}test::~test(){cout<<"~test()"<<endl;}int main(){test *t =new test;delete t;return 0;}


我们到程序的反汇编下去看对应的反汇编代码



跟进去call operator new,发现实际是用malloc分配空间



再看看delete





感兴趣的可以自己跟进一下,然后我们会发现最后不管newdelete还是mallocfree函数都会调用kernel中的heapAlocheapfree函数。