如果破坏是你需要的:
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
}