C++ object created with new, destroyed with free(); How bad is this?(C++对象用new创建,用free()销毁;这有多糟糕?)
问题描述
我正在修改一个相对较大的 C++ 程序,不幸的是,在我之前的人是否使用 C 或 C++ 语法并不总是很清楚(这是在一所大学的电气工程系,我们 EE 总是很想使用C 代表一切,不幸的是,在这种情况下,人们实际上可以侥幸逃脱).
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();
用delete thePacket;
还是free(thePacket);
销毁它有关系吗?
Does it matter whether it is destroyed with delete thePacket;
or free(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.
推荐答案
是的,这很重要.
对于使用new
获得的内存,您必须使用delete
.
For memory obtained using new
you must use delete
.
对于使用 malloc
获得的内存,您必须使用 free
.
For memory obtained using malloc
you must use free
.
new
和 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 memory, 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.
这篇关于C++对象用new创建,用free()销毁;这有多糟糕?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++对象用new创建,用free()销毁;这有多糟糕?
- 如何对自定义类的向量使用std::find()? 2022-11-07
- 从python回调到c++的选项 2022-11-16
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- C++ 协变模板 2021-01-01
- 静态初始化顺序失败 2022-01-01
- Stroustrup 的 Simple_window.h 2022-01-01
- 近似搜索的工作原理 2021-01-01
- 使用/clr 时出现 LNK2022 错误 2022-01-01
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- STL 中有 dereference_iterator 吗? 2022-01-01