限制C++变量的范围

Limit a C++ Variable's Scope

本文关键字:范围 变量 C++ 限制      更新时间:2023-10-16

我有一个C++程序,其形式如下:

int main(){
    int answer;
    ...
    MEMORY_CONSUMING_DATA_ARRAY temp;
    a few operations on the above;
    answer=result of these operations;
    ... //More code
}

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

我想在有限的范围内引入消耗内存的变量(类)以产生结果,然后将其销毁。帮助程序函数可以轻松做到这一点,但在我工作的场景中似乎有点矫枉过正。

关于如何实现这一目标的任何想法?

谢谢!

如果你需要销毁:

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

因此,这将适用于由动态分配支持的集合/对象,例如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
}

与堆栈分配相比:

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
}

Justin 的回答很好,但如果你一次又一次地执行此操作,那么你可能需要重用这个内存。

编辑

如前所述,静态将使内存不分配在堆栈上,这可能会使您受益,如果您每次都需要将内存清零,这也是可选的,如果您每次都要复制相同的数量并且不会读取超过这一点,那么您可以保存对零内存或其他初始化调用的调用。

int main(){
    int answer;
    ...
    {
      static MEMORY_CONSUMING_DATA_ARRAY temp; // make this static or a member perhaps
      temp = 0; // initialise it every time to clear the memory or zeromemory or other op
      a few operations on the above;
      answer=result of these operations;
    }
    ... //More code
}