限制C++变量的范围

Ric*_*ard 2 c++ scope

我有一个C++程序,具有以下形式:

int main(){
    int answer;

    ...

    MEMORY_CONSUMING_DATA_ARRAY temp;
    a few operations on the above;
    answer=result of these operations;

    ... //More code
}
Run Code Online (Sandbox Code Playgroud)

也就是说,我有一小块代码,似乎不保证自己的功能,但使用了大量的内存.

我想在一个有限的范围内使存储器消耗变量(一个类)存在以产生一个结果,然后将其销毁.辅助函数可以很容易地做到这一点,但在我正在工作的场景中似乎过度杀戮.

有关如何实现这一点的任何想法?

谢谢!

jus*_*tin 13

如果您需要破坏:

int main() {
    int answer;

    ...
    { // << added braces
      MEMORY_CONSUMING_DATA_ARRAY temp;
      a few operations on the above;
      answer=result of these operations;
    }
    ... //More code
}
Run Code Online (Sandbox Code Playgroud)

这样可以用于动态分配支持的集合/对象,例如std::vector.

但对于大堆栈分配......你是编译器的怜悯.编译器可能会决定在函数返回后清理堆栈,或者可以在函数内逐步执行清理.当我说清理时,我指的是你的功能所需的堆栈分配 - 而不是破坏.

为了扩展这个:

破坏动态分配:

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
}
Run Code Online (Sandbox Code Playgroud)

与堆栈分配:

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
}
Run Code Online (Sandbox Code Playgroud)

  • @Richard正确.该语言没有指定在"... //更多代码"执行时是否"返回"分配.它将超出范围,但堆栈位置可能会也可能不会恢复.换句话说,语言是否定义了`MEMORY_CONSUMING_DATA_ARRAY temp;`使用的区域是否在函数内重用. (2认同)