Raw Pointers from TFile Get<TTree>

In the following, I purposefully put a TFile on the heap.

TFile * myFile = new TFile("myCoolFile.root");

and read a TTree from the file

TTree * myTree = (TTree*) myFile->Get<TTree>("myCoolTree");

My Questions are:

  1. How do I de-allocate the resources? Should I close the file and delete the pointers?
myFile->Close();
delete myFile;
delete myTree;
  1. Is there any way I can avoid using raw pointers? I understand that I can put TFile on the stack, but is there a way I can retrieve a reference-like view of the TTree via Get instead of a pointer?

The TTree is co-own by the user and the TFile. So you can do either:

delete myTree;
delete myFile;

or simply

delete myFile; // This will delete the TTree

Related, the Close call will also delete the TTree object.

You can hold the TFile and TTree in a unique_ptr :

   std::unique_ptr<TFile> myFile{TFile::Open("myCoolFile.root")};
   std::unique_ptr<TTree> myTree{myFile->Get<TTree>("myCoolTree")};
1 Like