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

**URL:** <https://root-forum.cern.ch/t/how-to-properly-delete-ttree-and-tgraph-and-renew-them/55351>\
**Category:** Newbie\
**Tags:** root\
**Created:** [June 19, 2023, 1:50pm UTC](https://root-forum.cern.ch/t/how-to-properly-delete-ttree-and-tgraph-and-renew-them/55351 "2023-06-19T13:50:49Z")\
**Posts on this page:** 1\
**Showing post:** 2

<div class="post-metadata">

**Author:** ![vpadulan](https://root-forum.cern.ch/user_avatar/root-forum.cern.ch/vpadulan/32/25315_2.png) [@vpadulan](https://root-forum.cern.ch/u/vpadulan)\
**Post date:** [June 19, 2023, 2:57pm UTC](https://root-forum.cern.ch/t/how-to-properly-delete-ttree-and-tgraph-and-renew-them/55351/2 "2023-06-19T14:57:21Z")

</div>

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

```cpp
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.

---

_[View the full topic](https://root-forum.cern.ch/t/how-to-properly-delete-ttree-and-tgraph-and-renew-them/55351)._
