C ++:删除与免费和性能 [英] C++: delete vs. free and performance

查看:64
本文介绍了C ++:删除与免费和性能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  1. 考虑:

  1. Consider:

char *p=NULL;
free(p) // or
delete p;

如果我在p上使用freedelete会发生什么?

What will happen if I use free and delete on p?

如果程序需要很长时间才能执行(例如10分钟),是否可以将其运行时间减少到5分钟?

If a program takes a long time to execute, say 10 minutes, is there any way to reduce its running time to 5 minutes?

推荐答案

关于new/delete和malloc/free的一些性能说明:

Some performance notes about new/delete and malloc/free:

malloc和free 不要分别调用构造函数和解构函数.这意味着您的类不会自动初始化或取消初始化,这可能很糟糕(例如,未初始化的指针)!但是,对于象char和double这样的POD数据类型来说,这无关紧要,因为它们实际上没有ctor.

malloc and free do not call the constructor and deconstructor, respectively. This means your classes won't get initalized or deinitialized automatically, which could be bad (e.g. uninitalized pointers)! This doesn't matter for POD data types like char and double, though, since they don't really have a ctor.

新建并删除调用构造函数和反构造函数.这意味着您的类实例将自动初始化和取消初始化.但是,通常会出现性能下降的情况(与普通分配相比),但这会更好.

new and delete do call the constructor and deconstructor. This means your class instances are initalized and deinitialized automatically. However, normally there's a performance hit (compared to plain allocation), but that's for the better.

我建议与new/malloc用法保持一致,除非您有理由(例如重新分配).这样,您的依赖关系就更少了,从而减少了代码大小和加载时间(不过仅是一个小巧).另外,您不会通过释放分配给new的东西或删除分配给malloc的东西来搞乱. (这很可能会导致崩溃!)

I suggest staying consistent with new/malloc usage unless you have a reason (e.g. realloc). This way, you have less dependencies, reducing your code size and load time (only by a smidgin, though). Also, you won't mess up by free'ing something allocated with new, or deleting something allocated with malloc. (This will most likely cause a crash!)

这篇关于C ++:删除与免费和性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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