This may be an old question but I still do not really understand this issue in ROOT and can only find fragment answers.
My questions are that
when I create a pointer using new, what are the rules for me to delete the pointer? In c++, we always clean the pinter and may use smart pointer. I noticed that in ROOT macros, this is not always true. Another case if I use ROOT classes in my c++ program, what are the rules there?
What if I have an container with pointer as element? Is there any differences between ROOT macros and application?
The rules for memory management are the same for macro and C++ (except that using smart pointer is a bit harder in interpreted code).
[quote]what are the rules for me to delete the pointer?[/quote]The rule (and that is true for any C++ code/library) depend on what is the type you are pointed to. The rules regarding the ROOT classes are details in the object ownership chapter of the ROOT Users’ Guide (For example a TTree object will be attached to the TFile it’s data is store in and deleting the TFile will delete the TTree object hence making the explicit deletion of the TTree uncessary).
Hi, Philippe,
Thank for your answers. I was thinking that ROOT environment has some garbage collector,so macro users don’t care about the undeleted pointers. I was wrong and will take a look at the ownership chapter again.
Would you mind explaining how Tfile can own a TTree? For example, you can have a file in c++ and you can write string to file, but file and string are two different objects. Thanks.
[quote]Would you mind explaining how Tfile can own a TTree?[/quote]This should be detailed in the ‘Object Ownership’ chapter of the User’s Guide. Let me know if it still unclear after reading it.
Thanks. My question is more about why ROOT designs that way such that TFiles owns a TTree. It must has some benefits which I don’t appreciate yet. But I can feel the burden to memorize these new rules in addition all the exceptions in c++!
[quote]why ROOT designs that way such that TFiles owns a TTree.[/quote]This is to simplify the most common interactive
use which ‘just’ need to be:root [] f = new TFile(...);
mytree->Draw("variables");
somehisto->Draw("...");
....
delete f;(i.e. saving the keeping track of the histograms and trees extracted from the file).
Do you mean user may delete file first, then delete tree which screws the program. It makes sense now to me that we have to add some layers for interactive usage of c++. Many thanks.