简体   繁体   中英

Do objects in C/C++ get garbage collected after the program exits?

在C和C ++中,假设我没有使用智能指针或任何其他奇怪的垃圾收集机制,那么程序退出时是否会释放内存(收集垃圾)?

When a process terminates, the OS removes the virtual memory which had been assigned to it.

Since the entirety of its address space goes away, so do all the objects within.

However, this is not the same as C++ garbage collection: no destructors get called. The memory just... quietly returns to the operating system.

在几乎所有平台上,操作系统都会在进程退出时恢复进程拥有的所有资源(某些类型的共享资源,例如SYSV-IPC)。

Yes, any memory you don't free will be automatically freed by the operating system when your program exits. This means it's generally safe to call exit() at any time, though you need to be careful about other resources that aren't automatically freed, like global atoms on Windows and named pipes and others.

Memory does not get garbage collected at all in C++, in that destructors won't be run, etc. However, as part of cleaning up the process when the program exits, it will free any memory or other resources that were used by the program. Other resources might be locks, shared memory, network connections, file handles, etc.

This is not specified in C.

The C Standard says nothing about that but common OS deallocate the memory for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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