Hi Christian, Sorry for answering only now to your mails. cstrato@EUnet.at wrote: > > Dear Rooters > > I am writing code which I compile as library "Mylib.so". I am used to > create > my objects with "new obj" and delete them after use with "delete obj". > > However, when using root, in the following cases I am not sure what to > do: > > 1, "obj = gDirectory->Get("name");": > Does this create the object or do I have first to call "obj = new > TObject"? The object is created by Get. You must cast to the expected class. MyClass *obj = (MyClass*)gDirectory->Get("name"); > Do I have to call "delete obj" afterwards? Yes or No. If the object you are reading is a TH1 or TTree, these objects are automatically added to the list of objects in memory associated to the current directory. When you will close the file, these objects will be automatically deleted. Of course, you can delete them before closing the file. For all the other objects, it is your responsability to delete the objects. > > 2, "tree->MakeClass("MyClass");": > When I have "tree->Branch("br","ClassA",&classA,64000,0);" and call > MakeClass, > then the automatically generated code "MyClass.h" uses TTree, TBranch, > ClassA > without creating any of these classes first. > When I use this code in my library code, do I have to create these > classes first? No, the creation of these objects is automatic. See an example of use in the comments printed in MyClass.C. Simply do: MyClass xx; xx.GetEntry(i); See MyClass constructor and the function MyClass::Init in MyClass.h. > At the moment my code creates these classes in a constructor (new TTree, > new TBranch, > new MyClass) and calls "delete tree, delete br, delete classA" in a > destructor. > > This code works fine, nevertheless my question is: > Is this the correct way to do? I repeat, you do not have to create these objects. > Do I create a memory leak by doing this? Probably not. When you close the file containing these objects, they are automatically deleted from memory. > Is it not necessary to create these classes? > > At last a general question: > How can I test whether my code produces memory leaks? > Root has a facility to detect memory leaks by monitoring the number of classes created/deleted (see TObjectTable). To use this facility, edit the file .rootrc if you have this file or $ROOTSYS/system.rootrc and edit/add the two following lines: Root.MemStat: 1 Root.ObjectStat: 1 In your code, for example in your loop where you call tree.GetEntry(i), you can insert the line gObjectTable->Print(); This line will print the list of active classes and the number of instances for each class. By comparing consecutive Prints, you can see objects that you forgot to delete. Note that this method cannot show leaks coming from the allocation of non objects or classes unknown to Root. Rene Brun
This archive was generated by hypermail 2b29 : Tue Jan 01 2002 - 17:50:37 MET