你能在 C++ 中混合使用 free 和构造函数吗?
我正在阅读这个问题:
在什么情况下使用 malloc 与 new?
有人提出使用 malloc 的原因之一是如果您要使用 free。
我想知道:在 C++ 中混合自由调用和构造函数初始化是否有效?
即
我可以说:
my_type *ptr = new my_type;
free(my_type);
这是否在某种程度上无效或更糟糕
my_type *ptr = new my_type;
delete my_type;
除了它不是 c++ 的事实之外,
?同样,你能做相反的事吗?你能说,
my_type *ptr = (my_type *)malloc(sizeof(my_type));
delete my_type;
如果这是重复的,请合并,我搜索过,但没有看到关于 malloc/delete/new/free 的问题。
Possible Duplicate:
Is there any danger in calling free() or delete instead of delete[]?
I was reading this question:
In what cases do I use malloc vs new?
Someone raised that one reason to use malloc was if you were going to use free.
I was wondering: Is it valid to mix a free call and a constructor initialization in C++?
i.e.
Can I say:
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;
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;
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
不,它是无效的。不保证
new
将使用malloc
或delete
将使用free
。此外,使用
free
而不是delete
将跳过my_type
的析构函数。如果my_type
本身持有一些资源,这些资源将会被泄漏。同样,malloc 将跳过构造函数,因此变量可能处于无效状态。No it is invalid. There is no guarantee that
new
will usemalloc
ordelete
will usefree
.Moreover, using
free
instead ofdelete
will skipmy_type
's destructor. Ifmy_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.不,不是。
malloc、calloc、realloc ->免费
新->删除
新的[]->删除[]
No it is not.
malloc,calloc,realloc -> free
new -> delete
new[] -> delete[]
不,这是无效的。
malloc
(和其他 C 分配函数)必须与free
匹配,new
必须与delete
匹配,并且new []
必须与delete []
匹配。虽然如果没有析构函数代码,您的编译器不一定会执行任何不同的操作,但这不是您应该依赖的东西。主要区别在于new/delete调用对象的构造函数和析构函数; malloc 和 free 只是将其视为原始的、无类型的内存。
No, this is not valid.
malloc
(and other C allocation functions) must be matched withfree
,new
must be matched withdelete
, andnew []
must be matched withdelete []
. While your compiler may not necessarily do anything differently if there is no destructor code, this is not something you should rely on.The main difference is that new/delete call the constructor and destructor of an object; malloc and free just treat it as raw, untyped memory.
free()
不调用析构函数。它只是释放内存,不问任何问题。new
/delete
不保证使用malloc()
作为其内存分配器;free
甚至可能不知道你扔给它的内存free()
does not call the destructor. It just deallocates the memory, no questions asked.new
/delete
is not guaranteed to usemalloc()
as its memory allocator;free
might not even know about the memory you're throwing at it