2

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

int main(){
    int answer;

    ...

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

    ... //More code
}

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

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

关于如何做到这一点的任何想法?

谢谢!

4

2 回答 2

14

如果破坏是你需要的:

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
}
于 2012-05-08T18:35:31.150 回答
3

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

编辑

正如所指出的那样,静态会使内存不在堆栈上分配,这可能对您有利,如果您每次都需要将内存归零,如果您每次都复制相同的数量并且不读取,这也是可选的过了这一点,您可以保存对 zeromemory 或其他初始化调用的调用。

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
}
于 2012-05-08T18:40:02.180 回答