当程序退出时,是否有理由在C ++中调用delete?

编程入门 行业动态 更新时间:2024-10-22 17:38:04
本文介绍了当程序退出时,是否有理由在C ++中调用delete?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在我的C ++ main 函数中,例如,如果我有一个指向使用堆内存(而不是堆栈内存)的变量的指针 - 这是自动释放后我的应用程序退出?我会假设这样。

In my C++ main function, for example, if I had a pointer to a variable which uses heap memory (as opposed to stack memory) - is this automatically deallocated after my application exits? I would assume so.

即使如此,是最好的做法是总是删除堆分配,即使你认为它们永远不会在内存被自动释放的情况下使用退出?

Even so, is it good practice to always delete heap allocations even if you think they will never be used in a situation where the memory is automatically deallocated on exit?

例如,这是否有任何意义?

For example, is there any point in doing this?

int main(...) { A* a = new A(); a->DoSomething(); delete a; return 0; }

我在想我可能或其他人的refactors)代码并把它放在应用程序的其他地方, delete 是真正neccecary。

I was thinking maybe in case I refactor (or someone else refactors) that code and puts it elsewhere in the application, where delete is really neccecary.

正如Brian R. Bondy(它具体讨论了C ++中的含义)的答案,Paul Tomblin还有一个

As well as the answer by Brian R. Bondy (which talks specifically about the implications in C++), Paul Tomblin also has a good answer to a C specific question, which also talks about the C++ destructor.

推荐答案

重要的是明确地调用delete,因为你可能在析构函数中有一些代码要执行。像可能写一些数据到日志文件。如果你让操作系统为你释放你的内存,你的代码在析构函数中将不会被执行。

It is important to explicitly call delete because you may have some code in the destructor that you want to execute. Like maybe writing some data to a log file. If you let the OS free your memory for you, your code in your destructor will not be executed.

大多数操作系统将在程序结束时释放内存。但是这是一个好的习惯,自己释放它,就像我上面说的操作系统不会调用你的析构函数。

Most operating systems will deallocate the memory when your program ends. But it is good practice to deallocate it yourself and like I said above the OS won't call your destructor.

对于调用delete一般来说,是的,你总是想调用删除,否则你将有一个内存泄漏在您的程序,这将导致新的分配失败。

As for calling delete in general, yes you always want to call delete, or else you will have a memory leak in your program, which will lead to new allocations failing.

更多推荐

当程序退出时,是否有理由在C ++中调用delete?

本文发布于:2023-11-29 08:34:22,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1645884.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:有理由   程序   delete

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!