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()销毁;这有多糟糕?
基础教程推荐
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- CString 到 char* 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
