清除在main()中分配的堆栈内存?

时间:2018-08-22 16:09:14

标签: c++

我一直记得堆指针已经很久了,这反过来促使我在编写时考虑它们的含义,而我意识到我不知道该如何或什至可能分配完内存后,从内存中清除在main()中声明的堆栈变量。

很明显,我只能使用struct和destructor或类似方法,但是我可以说要删除main()中声明的堆栈上的数组,可以吗?

4 个答案:

答案 0 :(得分:4)

  

我想删除main()中声明的堆栈上的数组   有可能吗?

是的。

在main()(以及大多数使用自动变量的地方)中,您可以通过关闭包含范围来触发dtor。

示例:

int main(int argc, char* argv[])
{
   int retVal = 0;
   int arr[10];
   T610_t  t610;
   retVal = t610.exec(argc, argv);
   // ...
   // ...  // t610 exists to end of main() scope.
   // ...  // arr[10] exists to end of main() scope
   return retVal;
}

实例t610(用户定义的T610_t类型)持续了程序的生命周期,即使在exec()返回retVal之后不使用该实例也是如此。


相反:

int main(int argc, char* argv[])
{
   int retVal = 0;
   {
      int arr[10];
      T610_t  t610;
      retVal = t610.exec(argc, argv);
   }
   // ...   // no t610 instance exists, and arr[] is no longer accessible
   // ...
   // ...
   // ...
   return retVal;
}

在exec()返回retVal之后,在关闭括号处调用实例t610的dtor。 arr [10]也不再存在。

右括号后的所有行都无法访问T610_t,也无法访问arr [10],并且“释放”在“小范围”中的任何自动内存都将被“释放”以供重复使用。 (例如,另一个T610_t实例...)

任何对T610_t使用的空间的“清除”都取决于dtor的工作以及清除的含义。因此,例如,可以用0填充T610_t的数组数据属性(以“清除”它),并且dtor也会释放内存以供重复使用。请记住,没有“新”操作时请勿删除。

答案 1 :(得分:2)

不,您不能真正从当前本地范围内删除变量。

您不必担心-编译器会处理那里的所有事情。

如果您担心隐私问题,当然可以在使用后清空该变量。

答案 2 :(得分:2)

一个半答案,用来说明技巧,而实际答案却被忽略了。 (编辑:发布此消息时,疏忽已改变)

如果您在堆栈上分配了一大块内存(自动分配),并且需要返回该内存而不从函数返回,则可以通过调用另一个函数来引入新作用域

apply plugin: 'application'

mainClassName = "game.core.Game"

repositories {
    jcenter()
}

dependencies {
    compile 'org.apache.commons:commons-math3:3.6.1'
    implementation 'com.google.guava:guava:23.0'
    testImplementation 'junit:junit:4.12'
}

jar {
    baseName = 'HangmanGame'
    version = '2.00.0'
    manifest {
        attributes(
        'Class-Path': configurations.compile.collect { it.getName() }.join(' '),
        'Main-Class': 'game.core.Game'
        )
    }
}

或者通过用花括号将相关代码括起来

int get_and_compute()
{ 
    int array[1024*1024];
    read_in_a_lot_of_inputs(array);
    return compute_stuff_with__array(array);
} 

int main()
{
    int result = get_and_compute();
    // now you have enough memory to call 
    job_that_takes_a_lot_of_RAM(result);
}

大多数时候,我更喜欢选项1,添加一个功能,但是有时候,额外的功能没有多大意义。选择最容易阅读,编写和维护的选项。

答案 3 :(得分:1)

  

我想删除在main()中声明的堆栈上的数组,可以吗?

只需让执行超出声明自动变量的范围即可:

int main() {
    {
        int arr[10];
    }
    // arr is destroyed, and further local variables can reuse its memory
}
相关问题