简体   繁体   中英

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. 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() ). You will find the size is zero, every time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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