To delete or not to delete TDirectory's


I have a long-standing doubt that I have been solving without knowing if tihs is the right way to do it. So I’d like a suggestion.

I have a TFile with many nested TDirectory’s inside. I am interested in the most bottom one’s which are called “module_*” . What I am using to navigate and be able to collect all the TDirecory’s I am interested in is a function that I call iteratively and takes the TKey of a directory as input. You can find a simplified example in the attachment.

What I am sure is correct is to “delete” all the objects I get with TKey::ReadObj() once I know they are not a TDirectory and therefore are not needed to continue the navigation. If I do not do that I continue to fill the memory with objects I do not need and this effect is clear when I quit the root session: it takes ages to quit.

What I don’t know if it has to be done or not is to delete the objects when they are TDirectory’s once I do not need them anymore (for example because I have finished to navigate below it). In the attached example the two possible statements are indicated with an arrow. My experience is that if I include this “delete” statements, then I have problems (crashes) if I have to access the file later on using the TKey’s of the directories I am interested in (the navigation is used to create a list of TKey*'s of those TDirectory’s), while if I do not delete them I have no problem. So, presently, I am not deleting them but I’d like to know if this is the expected behaviour: does “delete” behaves differently if the object I get from TKey::ReadObj() is a TDirectory or not?

                                           Thanks in advance



test_navigator.C (1.46 KB)

In case of a key being a TDirectory, you should not call key->ReadObj, just cd to the directory. To test if a key is a TDirectory without reading the object in memory test key->GetClassName()


Thanks Rene, it works nicely.

At this point I have another question. In my navigation I used to collect in a TList the TKey* of the TDirectory’s I am interested in. In this way I accessed the directories, when needed, with TKey::ReadObj() .

Now that you suggested me not to use ReadObj() to get the TDirectory* would it be safe to collect in the TList the TDirectory* directly? My doubt is that the TDirectory objects are created and destructed depending on which is the current directory and therefore it would be useless to collect pointers which are no more valid later on.
Is it the case or, instead, the TDirectory* pointers point to object which are not deleted?



[quote]would it be safe to collect in the TList the TDirectory* directly? [/quote]Yes it is safe.

[quote]instead, the TDirectory* pointers point to object which are not deleted? [/quote]The TDirectory object are deleted only when the TFile object is Closed.