使用new创建的C ++对象,使用free()销毁;这有多糟糕? [英] C++ object created with new, destroyed with free(); How bad is this?
问题描述
我正在修改一个相对较大的C ++程序,不幸的是,在我之前是否有人使用C或C ++语法(这是在大学的电气工程部门,我们EE总是试图使用
I am working on modifying a relatively large C++ program, where unfortunately it is not always clear whether someone before me used C or C++ syntax (this is in the electrical engineering department at a university, and we EEs are always tempted to use C for everything, and unfortunately in this case, people can actually get away with it).
但是,如果有人创建了一个对象:
However, if someone creates an object:
Packet * thePacket = new Packet();
用删除或
免费(thePacket);
?
我意识到delete调用析构函数,而free()没有,但Packet没有析构函数。我在这里有一个可怕的时间呆在内存管理沼泽,我认为这可能是许多问题之一。
I realize that delete calls the destructor while free() does not, but Packet does not have a destructor. I am having a terrible time stuck in a memory management swamp here and I'm thinking this may be one of the many problems.
推荐答案
p>是的,没关系。对于使用 new
获得的内存,您必须使用 delete
并使用 free
对于从 malloc
获取的那些。 new
和 malloc
可以在内部使用不同的数据结构来跟踪其分配内存的位置和位置。所以为了释放memmory,你必须调用知道这些数据结构的相应的函数。然而,将这两种类型的存储器分配混合在一段代码中通常是个坏主意。
Yes it does matter. For memory obtained using new
you must use delete
and use free
for those obtained from malloc
. new
and malloc
may use different data structures internally to keep track of what and where it has allocated memory. So in order to free memmory, you have to call that corresponding function that knows about those data structures. It is however generally a bad idea to mix these two types of memory allocation in a piece of code.
这篇关于使用new创建的C ++对象,使用free()销毁;这有多糟糕?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!