Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top