Local TH1D with same name overwritten

Hi rooters,

this is a feature I have been noticing a lot but everytime I make a workaround and forget about it but it is becoming so anoying that I think it is better to post because it can be something silly that I am doing.

I have a loop in which I declare a temporary TH1D and work like so:

for (int i = 0; i < m_sys_names.size(); ++i)
        TH1D up("up_var","up_var",nbins,low,high);
        TH1D down("down_var","down_var",nbins,low,high);
        ... keep working...

where the function modifyHistogram just makes some adjustments to the histograms. The thing is that it seems to remember what the histogram was in the iteration before. The fist one it worked as supposed and after all iterations I get a superposed modifications of all histograms in the loop, even though the up and down histograms are created in each iteration. It is like I am modifiyng the same histogram as the iteration before.

The only way to solve this is to give the histogram a different name in each iteration… which I think is weird since those histogram are crated in each iteration, so it seems like ROOT remembers the names and the object.

Is there a simple way of using this temporary histogram without having to give a different name in each iteration? also, is there any memory issue with the fact that you are declaring new histogram in each iteration?

Thanks a lot in advance!

ROOT manages the lifetime of certain objects behind the scenes, and it identifies such objects by their name. Histograms are one such type of object, so unlike a regular C++ object or variable, it does have a remnant from previous iterations when you declare the new one. In principle your new TH1 should just overwrite the old one, but if you want to be safe, I think you have two options:

  1. as you already mentioned, give each a unique name. I like to use the TString::Format method to append a _%d with the loop index in the name.

  2. explicitly delete the TH1 after you are done with it. You can use the TH1::Delete() method for this.

Caveat: I have been wrong before about how ROOT memory management works and been yelled at on this forum by real experts. I haven’t learned my lesson yet and I am still trying to help people who have simple questions. I think my two solutions above will work, but perhaps my explanation of why they are needed is not technically correct.


Thanks jfcaron, I imagined that it was something like that.

Ok, I will then give different names to each hsitogram. If there is no problem from the memory point of view (eventually the objects get deleted) I don’t think that is a problem.