Root file and memory mecanism

I tried the following:

[code]TH1F* histo1 = new TH1F(“test”,“Test histogram”,10,1,10);
TH1F* histo2 = new TH1F(“test2”,“Test histogram 2”,10,1,10);

TFile* f = new TFile(“ntuple.root”);
TTree* t = (TTree*)f->Get(“CBNT/t3333”);

// Code for
// SetBranchAddresses, GetEntries and fill histogram
// Loop over all entries in t

TFile* hFile = new TFile(“pti.root”,“RECREATE”);

//Code for deletes and clean up[/code]

Now I’ve got a root file constaining two histograms test and test2

Now, if I do the same thing but after fill the histograms from t, close the TFile* f and open a new TFile* f = new TFile(“ntuple2.root”) and get a TTree* t = (TTree*)f->Get(“CBNT/t3333”) my histograms wanish.

Why and how is the TFile,TTree, TH1F etc connection work?


You should read carefull the chapter on Object Ownership in the ROOT Users’ Guide.

The linehisto1->SetDirectory(hFile); attached the histogram to the file and it will indeed be delete when the file is close.
To get what you expect use just:

TFile* hFile = new TFile("pti.root","RECREATE"); histo1->Write(); histo2->Write();