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

岁酱吖の 提交于 2019-11-30 05:59:43

问题


I'm trying to gain some memory saving in a C++ program and I want to know if I can use blocks as a scope for variables (as in Perl). Let's say I have a huge object that performs some computations and gives a result, does it makes sense to do:

InputType  input;
ResultType result;

{
    // Block of code
    MyHugeObject mho;
    result = mho.superHeavyProcessing();
}

/*
   My other code ...
*/

Can I expect the object to be destroyed when exiting the block?


回答1:


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.




回答2:


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




回答3:


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.




回答4:


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.



来源:https://stackoverflow.com/questions/581097/can-i-use-blocks-to-manage-memory-consumtion-in-c

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