简体   繁体   English

释放数组上的内存

[英]c++ - How to free up memory on an array

I am dealing with the following puzzling issue 我正在处理以下令人费解的问题

First of all, I have to open some files and do some operations. 首先,我必须打开一些文件并执行一些操作。 for these I have to define some arrays. 为此,我必须定义一些数组。 What I would like to do, is delete the array before going to the next file. 我想做的是在转到下一个文件之前删除数组。 I know that I could dynamically define the arrays, but 我知道我可以动态定义数组,但是

  1. I don't know a priori the size 我不知道先验的大小
  2. I was advised not to mess with dynamic allocation 建议我不要搞乱动态分配

So is there a way to "erase" a non dynamically-defined array? 那么,有没有办法“擦除”非动态定义的数组?

A sample code is the following 下面是一个示例代码

void Analyze(unsigned int first_run, unsigned int last_run, unsigned int last_segment){

    TFile *fin = new TFile(TString::Format("HPGe_%d_%d_%d.root", first_run, last_run, last_segment));
    for (int segm = 2; segm<=3; segm++){//loop for different files
        std::vector<double> left;
        std::vector<double> right;
        std::vector<int> amplitude;
        Function_that_fill_arrays_PUSHBACK(left, right, amplitude);
        for (int i=0; i<left.size(); i++){
            if (right[i]<=0.01){
                cout << "Left side : " << left[i] << ", Right side : " << right[i] << ", Amplitude : " << amplitude[i] << endl;
            }
        }
        DELETE ARRAYS HERE
    }// end of loop over files

}//end of function

Any idea on how can something like that be achieved? 关于如何实现这样的想法?

You don't need to do anything at all. 您根本不需要做任何事情。

The vectors left , right , and amplitude are all created locally within the body of the loop. 向量leftrightamplitude都在循环体内局部创建。 So each one is created anew (with zero elements, since that is how they are initialised) at the start of the loop body, and destroyed at the end - which releases the memory they use ..... on EVERY iteration of the loop. 因此,在循环体的开头重新创建一个新元素(使用零个元素,因为这是它们的初始化方式),并在循环末尾销毁-这会在每次循环迭代时释放它们使用的内存... 。

You can check that by printing the sizes of the vectors immediately after they are declared (ie before the call of Function_that_fill_arrays_PUSHBACK() ). 您可以通过在声明向量后立即(即在调用Function_that_fill_arrays_PUSHBACK() )打印向量的大小来进行检查。 You will find the size is zero, every time. 您会发现大小每次为零。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM