简体   繁体   English

c ++程序结束时从内存释放指针?

[英]are pointers released from memory when c++ program end?

这是一个初学者的问题,但是我学习了使用c#进行编程的知识,现在我正在使用c ++,并且现在我正在使用指针,我知道在完成对它们的处理之后,当程序关闭时,我必须将其从内存中释放出来。他们从内存中移走还是留在那里?

When your program ends, all the memory it used (whether dynamically allocated or not) is returned to the operating system. 程序结束时,它使用的所有内存(无论是否动态分配)都返回给操作系统。 It doesn't matter if it's a C program, a C++ program, a C# program, or any other kind of program you might be writing. 不管是C程序,C ++程序,C#程序还是您可能正在编写的任何其他类型的程序,都没有关系。

Now, just because the OS will reclaim the memory doesn't mean you can be cavalier about memory management. 现在,仅因为操作系统将回收内存,并不意味着您可以更轻松地进行内存管理。 While your program runs, you should try to take care of freeing any memory you're done with. 在程序运行时,您应尝试释放完成的所有内存。 Not doing so will cause "memory leaks", and those can certainly affect your program and the system it's running on, at least while your program is running. 否则会导致“内存泄漏”,并且这些泄漏肯定会影响您的程序及其所运行的系统,至少在您的程序运行时。

Note that its not the pointer that needs deallocation but the pointed object. 请注意,不是需要释放的指针,而是指向的对象。

The answer depends on type of memory the pointers point to: 答案取决于指针指向的内存类型:

  • If the pointer points to automatic object then the objects are cleaned implicitly. 如果指针指向自动对象,则将隐式清除对象。
  • If the pointer points to objects allocated dynamically using new or new [] or malloc or calloc , then they need to be explicitly deallocated by resp calling delete or delete [] or free . 如果指针指向使用newnew []malloccalloc动态分配的对象,则需要通过resp调用deletedelete []free显式释放它们。

Note that it is advisable to Use dynamic allocations sparingly and if you must, Use Smart pointers instead of raw pointers. 请注意,建议您谨慎使用动态分配;如果必须,则使用智能指针而不是原始指针。

EDIT: 编辑:
If your question is: 如果您的问题是:
What happens if your program doesn't deallocate memory and exits? 如果您的程序没有取消分配内存并退出该怎么办?

Answer is: 答案是:
OS reclaims it. 操作系统对其进行了回收。 The OS simply takes back all the memory it allocated to a process it does not understand whether your program leaked memory or not. 操作系统只是收回分配给进程的所有内存,而该进程不了解程序是否泄漏了内存。
But it is always a good practice to clean up your own mess yourself. 但是,自己清理自己的混乱始终是一个好习惯。
If you have an class who's destructor does have code with side-effects then not calling delete on the dynamically allocated pointer results in Undefined Behavior and it renders your code completely dangling at compilers mercy. 如果您的类的析构函数确实具有带副作用的代码,则不对动态分配的指针调用delete导致未定义行为,这会使您的代码完全陷入编译器的摆布之下。

The memory allocated by you ( eg using the New keyword) will remain there unless you delete it! 您分配的内存(例如,使用New关键字)将保留在那里,除非您将其删除! If you are talking about the pointer itself, then yes! 如果您在谈论指针本身,那么可以! At the end of your program the pointer will just get wiped out! 在程序结束时,指针将被清除!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM