The result of the operator new in this code snippet is ‘lost’ on the 2nd line. i.e. there is a memory leak. You probably meant:
TH1F* h = (TH1F*)gDirectory->Get("HISTO");
The histogram is associated with the ‘current’ directory which is the file opened by the TChain. Consequently when this file is closed (the next call to MakeHisto), the histogram is deleted.
The solution with RDataFrame is superior but for completeness the following might work:
The problem has nothing to do with the “current” directory, nor with the “TChain”.
It is generated by the “HISTO(1000,-4,4)” string in the “Draw” expression.
{
// run this macro "as is", then replace "#if 1" with "#if 0" below and rerun
// (note: this macro needs the "hsimple.root" from "${ROOTSYS}/tutorials/")
TChain *t;
TH1 *h;
// ... first pass ...
std::cout << "gDirectory = " << gDirectory->GetName() << std::endl;
t = new TChain("ntuple");
t->Add("hsimple.root");
std::cout << "gDirectory = " << gDirectory->GetName() << std::endl;
// note: this will CREATE a new "HISTO"
t->Draw("px>>+HISTO(1000,-4,4)");
std::cout << "gDirectory = " << gDirectory->GetName() << std::endl;
h = (TH1*)gDirectory->Get("HISTO");
std::cout << "h = " << h << std::endl;
if (h) h->Print();
// ... second pass ...
std::cout << "gDirectory = " << gDirectory->GetName() << std::endl;
t = new TChain("ntuple");
t->Add("hsimple.root");
std::cout << "gDirectory = " << gDirectory->GetName() << std::endl;
#if 1 /* 0 or 1 */
// note: this will DELETE the existing "HISTO" and CREATE it anew
t->Draw("px>>+HISTO(1000,-4,4)");
#elif 1 /* 0 or 1 */
// note: this will REUSE and RESET the existing "HISTO"
t->Draw("px>>HISTO");
#else /* 0 or 1 */
// note: this will REUSE and ADD entries to the existing "HISTO"
t->Draw("px>>+HISTO");
#endif /* 0 or 1 */
std::cout << "gDirectory = " << gDirectory->GetName() << std::endl;
h = (TH1*)gDirectory->Get("HISTO");
std::cout << "h = " << h << std::endl;
if (h) h->Print();
}
// note: this will DELETE the existing "HISTO" and CREATE it anew
t->Draw("px>>+HISTO(1000,-4,4)");
This sounds like a bug (either in the doc or the code) as this looks like it should ‘Append’ to the histo if it exist rather than recreate it (because of the ‘+’).
Well". the “+” is neglected in case you explicitly define the histogram binning.
Try my small test macro replacing “#if 1” with “#if 0” and “#elif 1” with “#elif 0”.