动态内存管理

来源:互联网 发布:阿里云cdn加速配置 编辑:程序博客网 时间:2024/06/06 00:25


使用_alloc在栈上动态开辟内存,栈上开辟的内存有编译器自动维护,不需要用户显示释放。
new 申请空间失败时抛异常。

class Test{public:    Test()    {        _data = 0;        cout << "Test():" << this << endl;    }    ~Test()    {        cout << "~Test():" << this << endl;    }private:    int _data;};//void FunTest1()//{//  Test *p0 = (Test*)malloc(sizeof(Test));//malloc开辟的只是和test大小相同的一段空间//  Test *p1 = new Test;                   //并不是test//  free(p0);//  free(p1);//}//void FunTest2()//{//  Test *p0 = (Test*)malloc(sizeof(Test));//  Test *p1 = new Test;    //Test-->对象构造成功//  free(p0);//  //free(p1);//  delete p1;//}//void FunTest3()//{//  Test *p0 = (Test*)malloc(sizeof(Test));//  Test *p1 = new Test;//  delete p0;//  delete p1;//}//void FunTest4()//{//  Test *p0 = (Test*)malloc(sizeof(Test));//  Test *p1 = new Test;//  delete p0;//  free(p1);//}//void FunTest5()//malloc  delete[]程序崩溃//{//  Test *p0 = (Test*)malloc(sizeof(Test));//  Test *p1 = new Test;//  delete[] p0;//  free(p1);//}//void FunTest6()//new  delete[]程序崩溃//{//  Test *p0 = (Test*)malloc(sizeof(Test));//  Test *p1 = new Test;//  free(p0);//  delete[] p1;//}//void FunTest7()//{//  Test *p0 = (Test*)malloc(sizeof(Test));//  Test *p1 = new Test[10];//  free(p0);//  delete[] p1;//}void FunTest8()//new[] delete 程序崩溃{    Test *p0 = (Test*)malloc(sizeof(Test));    Test *p1 = new Test[10];    free(p0);    delete p1;}int main(){    //FunTest1();    //FunTest2();    //FunTest3();    //FunTest4();    //FunTest5();    //FunTest6();    //FunTest7();    FunTest8();    getchar();    return 0;}//#endif

FunTest1()
malloc/free new/free
new  free

FunTest2()
malloc/free new/delete 匹配使用

FunTest3()
malloc/delete new/delete

FunTest4()
malloc/delete new/free

FunTest7()
malloc/free new/delete[]
这里写图片描述

FunTest8()
malloc/free new[]/delete
程序崩溃

原创粉丝点击