New/Delete和Malloc/Free的对比

来源:互联网 发布:伊丽莎白镇 知乎 编辑:程序博客网 时间:2024/05/17 03:37
#include "iostream"using namespace std;//1 new/delete(操作符)作用手工分配内存(heap上)  malloc/free(函数)//2 new/delete int 基础类型//3 new/delete 数组//4 new/delete类//指针做函数参数class Test1{public:    Test1(int a, int b)    {        m_a = a;        m_b = b;        cout<<"构造执行"<<endl;    }    ~Test1()    {        cout<<"析构执行"<<endl;    }protected:private:    int m_a;    int m_b;};//c++中的new能自动的调用类的构造函数,delete能调用类的析构函数//malloc不会调用类的构造函数 free也不会调用类的析构函数// new/delete类void example(){    Test1 *p2 = (Test1 *)malloc(sizeof(Test1));    free(p2);    Test1 *p1 = new Test1(3, 4);    delete p1;}//二级指针修改实参int CreateTest1(Test1 **p){    Test1 *tmp = new Test1(5, 6);    *p = tmp;    return 0;}//引用方式修改实参int CreateTest2(Test1 * &myp){    myp = new Test1(5, 6);    return 0;}int  main(){    Test1 *p3 = NULL;    Test1 *p4 = NULL;    CreateTest1(&p3);    delete p3;    CreateTest2(p4);    delete p4;    system("pause");    return 0;}
0 0
原创粉丝点击