在学习C语言的时候, 我们学了malloc, 后来学习C++的时候, 又学了new, 那么malloc和new有什么区别呢?
首先, malloc是一个库函数, 返回值是void *形式的, 而new是一个运算符, 返回值类型与new的对象/变量的指针相同。
其次, new和delete的实现实际上是调用了malloc/free的。
最后, 介绍最重要的, 对于非内部类型来说, malloc是不能满足要求的, 因为malloc只是分配堆内存(不会调用构造函数), 而new是分配且内存且在此创建一个对象(会调用构造函数)。
先看代码:
#include <iostream>
using namespace std;
class A
{
private:
int x;
public:
A()
{
cout << "A" << endl;
}
};
int main()
{
A *q = (A *)malloc(sizeof(A)); // 不会调用构造函数
return 0;
}
#include <iostream>
using namespace std;
class A
{
private:
int x;
public:
A()
{
cout << "A" << endl;
}
};
int main()
{
A *q = new A; // 会调用构造函数
return 0;
}
我们再看看这个代码有什么问题:
#include <iostream>
#include <string>
using namespace std;
class A
{
public:
string str;
A()
{
cout << "A" << endl;
}
};
int main()
{
A *q = (A *)malloc(sizeof(A));
q->str = "hello"; // 运行error. 没有构造函数被调用, 所以, str根本就没有被初始化(string的构造函数没有被调用), 所以不能赋值
return 0;
}
调用malloc只是分配空间而已, 下面程序可以说明这点, 确实没有产生任何对象:
#include <iostream>
using namespace std;
class I
{
public:
int x;
I()
{
cout << "I" << endl;
}
};
class A
{
public:
I i;
A()
{
cout << "A" << endl;
}
};
int main()
{
A *q = (A *)malloc(sizeof(A));
q->i.x = 100; // 可以看到, 确实没有任何构造函数被调用, 所以没有任何对象产生
return 0;
}
下面看看new:
#include <iostream>
#include <string>
using namespace std;
class A
{
public:
string str;
A()
{
cout << "A" << endl;
}
};
int main()
{
A *q = new A; // 分配了堆空间, 且A的构造函数会被调用, string的构造函数也会被调用
q->str = "hello"; // ok
return 0;
}