如何删除C中的变量
发布时间:2020-12-16 10:13:40 所属栏目:百科 来源:网络整理
导读:我想在我的程序中释放ram. 即使我是新手,我也非常关心性能. string i_want_to_delete_this = "I don't want this cleared,but completely gone";/* I figured out */ i_want_to_delete_this.clear() /* simply sets thestring value to "". I want to be abl
我想在我的程序中释放ram.
即使我是新手,我也非常关心性能. string i_want_to_delete_this = "I don't want this cleared,but completely gone"; /* I figured out */ i_want_to_delete_this.clear() /* simply sets the string value to "". I want to be able to do this with every datatype! I want it completely gone,not even declared anymore. */ 解决方法
有3种变量.根据您管理内存的种类不同.
全局变量 它们位于程序的特殊部分.它们在程序启动时出现,在程序结束时消失.你无法做任何事情来回收全局变量占用的内存. 堆栈变量 局部变量和函数参数.它们出现在您的代码中.输入该变量的范围时会分配内存,并在离开范围时自动删除: { //beginning of the scope int foo = 42; // sizeof(int) bytes allocated for foo ... } //end of the scope. sizeof(int) bytes relaimed and may be used for other local variables 请注意,当启用优化时,可能会将局部变量提升为寄存器,并且根本不消耗RAM内存. 堆变量 堆是你自己管理的唯一一种记忆.在普通的C中,你使用malloc在堆上分配内存并免费释放它,例如 int* foo = (int*)malloc(sizeof(int)); //allocate sizeof(int) bytes on the heap ... free(foo); //reclaim the memory 请注意,foo本身是一个局部变量,但它指向堆内存的一部分,您可以在其中存储整数. 同样认为在C中看起来像: int* foo = new (int; //allocate sizeof(int) bytes on the heap ... delete foo; //reclaim the memory 当变量必须比范围长得多时,通常使用堆,通常取决于一些更复杂的程序逻辑. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |