Can I use blocks to manage memory consumtion in C++?

时间秒杀一切 提交于 2019-11-28 12:30:45

Yes, you can.

The destructor will be called as soon as the variable falls out of scope and it should release the heap-allocated memory.

Yes absolutely, and in addition to conserving memory, calling the destructor on scope exit is often used where you want the destructor to actually do something when the destructor is called (see RAII). For example, to create a scope based lock and release easily it in an exception safe way, or to let go of access to a shared or precious resource (like a file handle / database connection) deterministically.

-Rick

Just remember that any memory you allocate on the heap using new/malloc that is freed in the destructor probably won't be released back to the OS. Your process may hold onto it and the OS won't get it back until the process terminates.

Yes. It will be destroyed at the closing curly brace. But beware of allocating very large objects on the stack. This can causes a stack overflow. If you object also allocates large amounts memory, make sure it is heap allocated with new, malloc, or similar.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!