Limit a C++ Variable's Scope

c++, scope

Solution

if destruction is what you need:

int main() {
    int answer;

    ...
    { // << added braces
      MEMORY_CONSUMING_DATA_ARRAY temp;
      a few operations on the above;
      answer=result of these operations;
    }
    ... //More code
}

so that would work for a collection/object backed by a dynamic allocation, such as `std::vector`.

but for large stack allocations... you're at the compiler's mercy. the compiler may decide it's best to cleanup the stack after your function returns, or it may incrementally perform cleanup within the function. when i say cleanup, i am referring to the stack allocations your function required -- not destruction.

To expand on this:

Destruction of a dynamic allocation:

int main() {
    int answer;
    ...
    { // << added braces
      std::vector<char> temp(BigNumber);
      a few operations on the above;
      answer=result of these operations;
      // temp's destructor is called, and the allocation
      // required for its elements returned
    }
    ... //More code
}

versus a stack allocation:

int main() {
    int answer;
    ...
    {
      char temp[BigNumber];
      a few operations on the above;
      answer=result of these operations;
    }

    // whether the region used by `temp` is reused
    // before the function returns is not specified
    // by the language. it may or may not, depending
    // on the compiler, targeted architecture or
    // optimization level.

    ... //More code
}

Problem

I have a C++ program that has the following form: ``` int main(){ int answer; ... MEMORY_CONSUMING_DATA_ARRAY temp; a few operations on the above; answer=result of these operations; ... //More code } ``` That is, I have a small block of code which doesn't seem to warrant its own function, but which uses a great deal of memory. I'd like to bring the memory-consuming variable (a class) into existence within a limited scope to produce a result and then have it destroyed. A helper function would do this easily enough, but it seems like over-kill in the scenario in which I'm working. Any thoughts on how to accomplish this? Thanks!

Original source