您的位置:首页 > 其它

malloc和new的区别---当malloc和string相遇时, 容易出错

2016-01-01 21:46 501 查看
在学习C语言的时候, 我们学了malloc,(用来向系统申请内存空间),后来学习C++的时候, 又学了new(用来创建一个对象),

那么malloc和new有什么区别呢?

首先, malloc是一个库函数, 返回值是void *形式的, 而new是一个运算符, 返回值类型与new的对象or变量的指针相同。

其次, new和delete的实现实际上是调用了malloc/free的。

最后, 介绍最重要的, 对于非内部类型来说, malloc是不能满足要求的, 因为malloc只是分配堆内存(不会调用构造函数),

而new是分配且内存且在此创建一个对象(会调用构造函数)。string类型的变量在使用前是必须初始化的。

先看代码:

[cpp] view
plainc

#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;

}

[cpp] view
plaincopy





#include <iostream>

using namespace std;



class A

{

private:

int x;

public:

A()

{

cout << "A" << endl;

}

};



int main()

{

A *q = new A; // 会调用构造函数



return 0;

}



我们再看看这个代码有什么问题:

[cpp] view
plaincopy





#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只是分配空间而已, 下面程序可以说明这点, 确实没有产生任何对象:

[cpp] view
plaincopy





#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:

[cpp] view
plaincopy





#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;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: