1、new和delete成对使用
2、malloc、free 和 new、delete这两个可以混合使用
3、malloc、free 和 new、delete区别:malloc和free是函数,但new和delete是c++中的操作符。
new还可以触发类对象的构造函数,malloc在这一点上缺失了一些实用性。
同理delete也可以触发对象的析构函数,free不会调用对象的析构函数。
这样的话可能会存在一个风险。比如下面的例子
- #include <iostream>
- #include <cstring>
- using namespace std;
-
- class teacher
- {
- public:
- teacher(int id, const char *name)
- {
- cout<<"teacher(int id, const char *name) ...."<<endl;
- m_id = id;
- m_name = new char[strlen(name)];
- if (NULL != m_name)
- {
- strcpy(m_name, name);
- }
- }
-
- void SetTeacher(int id, const char *name)
- {
- m_id = id;
- m_name = (char *)malloc(strlen(name));
- if (NULL != m_name)
- {
- strcpy(m_name, name);
- }
- strcpy(m_name, name);
- }
-
- ~teacher()
- {
- cout<<"~teacher() ...."<<endl;
- if (NULL != m_name)
- {
- delete m_name;
- }
- }
-
- void Pinrt()
- {
- cout<<"id="<<m_id<<", name="<<m_name<<endl;
- }
-
- teacher(const teacher &another)
- {
- m_id = another.m_id;
- m_name = new char[strlen(another.m_name)];
- if (NULL != m_name)
- {
- strcpy(m_name, another.m_name);
- }
- }
-
- private:
- int m_id;
- char *m_name;
- };
-
- int main(void)
- {
- teacher *pt1 = (teacher *)malloc(sizeof(teacher));
- pt1->SetTeacher(11, "li4");
- pt1->Pinrt();
- free(pt1);
-
- cout<<"------------------"<<endl;
-
- teacher *pt2 = new teacher(10, "zhang3");
- pt2->Pinrt();
- delete pt2;
-
- printf("\n");
- return 0;
- }
-
执行的结果

我们可以看到,当我们使用malloc的时候,想要初始化成员变量,还需要额外定义一个显示的Set函数去初始化成员变量。使用new则完全可以调用类的有参构造函数。
上面仅仅是实用性上new比较方便,但是当free和delete的时候就发生的致命的错误。
我们的成员变量里面有指针,使用free的时候,只能释放掉teacher *pt1所指向的空间,而pt1中的成员变量m_name也是一个指针,在SetTeacher时所申请的空间并没有释放掉,这样就造成了内存泄露。
而delete pt2的时候,则会调用teacher类的析构函数,同时释放掉m_name所指向的空间。使内存不会泄露,达到保护的作用。

补充:
int *p = new int[10]; //在堆上申请10个int长度的空间
int *p1=new int(10);//在堆上申请1个int长度的空间,并初始化值设为10
这两句话是两个意思