Object ownership by TFile


Hopefully a straightforward question: If you “Get” an object (specifically a TTree or a TH1) from a TFile, and subsequently delete the TFile, is the object deleted in memory correctly, and so I do not need to worry about deleting it myself?

For example:

TFile* f = new TFile("myFile.root") TTree* myTree = (TTree*)f->Get("myTree"); TH1* myHist = (TH1*)f->Get("myHist"); delete f;

Is all of this ok in a memory management context, or has this got a potential memory leak? Can someone confirm it is not necessary to follow this with:

delete myTree; delete myHist;



TFile *f = new TFile("myFile.root") myTree myHist delete f myTree myHist
I believe this is different for a TGraph (and possibly some another classes, but I don’t know any comprehensive list of them) - if you retrieve it from a file, it will stay in memory after you close the file, so you will need to delete it manually.

BTW. I was once told that it’s better to do:

TTree *myTreePointer; f->GetObject("myTreeName", myTreePointer); TH1 *myHistPointer; f->GetObject("myHistName", myHistPointer); TGraph *MyGraphPointer; f->GetObject("myGraphName", myGraphPointer);


So from the CINT prompt (so I know this might be wrong because of that), if I open the file, get the hist and then delete the file, the pointer naturally still exists, but it points to an invalid part of memory. If I tried to, say, draw the histogram, then CINT crashes. I just want to know if this means the histogram has been properly cleaned up from memory or not?

And it would interesting to know what the difference between Get and GetObject is, since you point out GetObject is apparently better