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

Is there a reason to call delete in C++ when a program is exiting anyway?(当程序退出时,是否有理由在 C++ 中调用 delete?)

本文介绍了当程序退出时,是否有理由在 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;
}

我在想也许以防我重构(或其他人重构)该代码并将其放在应用程序中的其他位置,其中 delete 确实是必要的.

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 necessary.

除了 Brian R. Bondy 的回答(专门讨论了 C++ 中的含义),Paul Tomblin 也有一个 很好地回答了一个 C 特定问题,其中也谈到了 C++ 析构函数.

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,是的,你总是想调用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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:当程序退出时,是否有理由在 C++ 中调用 delete?

基础教程推荐