C++对象用new创建,用free()销毁;这有多糟糕? [英] C++ object created with new, destroyed with free(); How bad is this?

查看:34
本文介绍了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.

newmalloc 可以在内部使用不同的数据结构来跟踪它分配了内存的内容和位置.因此,为了释放内存,您必须调用知道这些数据结构的相应函数.然而,在一段代码中混合这两种类型的内存分配通常是一个坏主意.

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()销毁;这有多糟糕?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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