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

972 篇文章 327 订阅
309 篇文章 10 订阅

        在学习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;
}

     
 

 

        

  • 6
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 8
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值