您可以在C ++中混合使用free和构造函数吗? [英] Can you mix free and constructor in C++?

查看:72
本文介绍了您可以在C ++中混合使用free和构造函数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
拨打免费电话是否有任何危险( )还是删除而不是delete []?

Possible Duplicate:
Is there any danger in calling free() or delete instead of delete[]?

我在读这个问题:
在什么情况下我应该使用malloc与new? >

I was reading this question:
In what cases do I use malloc vs new?

有人提出使用malloc的一个原因是,如果您要使用免费的话.

Someone raised that one reason to use malloc was if you were going to use free.

我想知道:在C ++中混合免费调用和构造函数初始化是否有效?

I was wondering: Is it valid to mix a free call and a constructor initialization in C++?

我可以说:

my_type *ptr = new my_type;
free(my_type);

是否在某种程度上比以下情况无效或更糟?

Is that somehow invalid or worse than:

my_type *ptr = new my_type;
delete my_type;

除了不是c ++ ish的事实以外?

other than the fact that it's not c++ish?

同样,您能做相反的事情吗?你能说

Likewise, could you do the opposite? Can you say

my_type *ptr = (my_type *)malloc(sizeof(my_type));
delete my_type;

如果这是重复的,请合并,我进行了搜索,但没有看到关于malloc/delete/new/free的问题.

Please merge if this is a duplicate, I searched but didn't see a question along this lines exactly about malloc/delete/new/free asked.

推荐答案

否,它是无效的.无法保证new将使用mallocdelete将使用free.

No it is invalid. There is no guarantee that new will use malloc or delete will use free.

此外,使用free代替delete将跳过my_type的析构函数.如果my_type本身拥有一些资源,则这些资源将被泄漏.同样,malloc将跳过构造函数,因此变量可能处于无效状态.

Moreover, using free instead of delete will skip my_type's destructor. If my_type itself is holding some resources, those will be leaked. Similarly, malloc will skip the constructor so the variable may be in an invalid state.

这篇关于您可以在C ++中混合使用free和构造函数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆