简体   繁体   中英

C++ variables/objects and Heap Memory Management

I am a newbie to c++ .I've been writing programs that creates objects in heap memory,Unfortunately i never de-allocated the memory using delete operator that i have allocated using new operator.Will it be recycled/refreshed when the system boots or will it be still allocated and produce memory errors such as "out of memory" in future ?
is there any serious problem if the memory has not been de-allocated ?
until now ,my programs are smaller and terminated once i verified the results.
Thanks for your reply..:D

In theory not deleting your memory could cause memory leaks which persist after your program terminates. In practice, any modern OS will automatically release all the memory that was allocated by your program when it exits.

That doesn't mean not deleting your memory is safe, however. Objects could have destructors which need to perform vital cleanup. If you don't delete them, their destructors won't be called.

It's actually quite easy to manage your memory in modern C++ using local variables to store your objects (instead of pointers), containers and smart pointers. You should learn about them.

It will be recycled/refreshed when the system boots. The OS will take of it when the program exits. Also, do not worry about any leaks when the system reboots.

While memory leaks won't persist in the system's memory pool after terminating the program, it's bad practice to rely on a reset to clean up the lost allocations.

If you have access to a newer C++11 compiler and are interested in preventing leaks, I suggest you check out these two classes from the standard library. In general, their usage will prevent the most common type of resource leaks with dynamic memory.

std::shared_ptr

std::unique_ptr

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