在我的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?
发布评论