例如找出令人信服的权威C++中间malloc与new

例如找出令人信服的权威C++中间malloc与new  

问题:   

非常多人都知道malloc与new都是用来申请空间用的,开辟空间来源于堆中。

可是在C++中却非常少用malloc去申请空间,为什么?


以下小编会以一个非常有说服力的样例来说明。相信大家一看就能明确。


C++程序的格局可分为4个区,注意是“格局”,

1、全局数据区     //当中全局变量,静态变量是属于全局数据区

2、代码区     //全部的类和非成员函数的代码都存放在代码区

3、栈区    //为成员函数执行而分配的局部变量的空间都在栈区

4、堆区 //剩下的那些空间都属于堆区

当中全局变量,静态变量是属于全局数据区。全部的类和非成员函数的代码都存放在代码区。为成员函数执行而分配的局部变量的空间都在栈区。剩下的那些空间都属于堆区。


以下来写个简单的样例:malloc.cpp

#include <iostream>
using namespace std;
#include <stdlib.h>

class Test{
    public:
        Test(){
            cout<<"The Class have Constructed"<<endl;
        }   
        ~Test(){
            cout<<"The Class have DisConstructed"<<endl;
        }   
};

int main(){
    Test *p = (Test*)malloc(sizeof(Test));
    free(p);
    //delete p;
    return 0;
}

编译执行:The Class have DisConstructed

结果是没有调用构造函数。从这个样例能够看出,调用malloc后,malloc仅仅负责给对象指针分配空间。而不去调用构造函数对其初始化。而C++中一个类的对象构造,须要是分配空间。调用构造函数。成员的初始化,或者说对象的一个初始化过程。通过上述样例希望大家在使用C++中尽量不要去使用malloc。而去使用new。

<span style="font-size:14px;">#include <iostream>
using namespace std;
#include <stdlib.h>

class Test{
    public:
        Test(){
            cout<<"The Class have Constructed"<<endl;
        }   
        ~Test(){
            cout<<"The Class have DisConstructed"<<endl;
        }   
};

int main(){
  //Test *p = (Test*)malloc(sizeof(Test));
    Test *p = new Test;
    cout<<"test"<<endl;
    
    //free(p);
    delete p;

    return 0;
}</span>


执行结果例如以下:

The Class have Constructed

 The Class have DisConstructed

假设想更加系统了解C++ new/delete,malloc/free的异同点,能够參看“深入C++ new/delete,malloc/free解析”了解详情。


版权声明:本文博客原创文章。博客,未经同意,不得转载。

posted @ 2015-07-24 16:05  phlsheji  阅读(289)  评论(0编辑  收藏  举报