How to properly delete TTree* and TGraph* and renew them

Hi @Crisps ,

I cannot stress this enough, please refrain absolutely from implementing your code with the pattern you show. No new or delete statements should be visible in user code in modern C++ applications. Try to reframe your application so that ideally you don’t need raw pointers, or if you strictly need them then the lifetime and ownership of objects should be controlled and understandable. Let me give you an example

TTree *myTree;
for (condition){
    std::unique_ptr<TFile> f{TFile::Open("myfile.root")};
    myTree = f->Get<TTree>("myTree");
    // use myTree in the loop
   // CRUCIAL: test the raw pointer
   if(myTree){
        // use it after the check, otherwise you could have a nullptr
   }
   // Anything that is created manually inside the loop, shouldn't be created with `new`
   TGraph myGraph{};
    TH1D myTH1D{};
}

In the example above, it is clear that TTree * is just a view on the tree owned by the TFile. Since it is wrapped by a unique_ptr the management will be done automatically and both the tree and file will be deleted appropriately at the end of the scope.

4 Likes