Can I use smart pointers freely or do I need to account for ROOT's hidden (global) state?

I like to keep up to date with modern C++ practices, so I was wondering, are there any pitfalls associated with adopting smart pointers with the ROOT classes, anything to know about regarding ROOT’s hidden state?

Smart pointers are all about ownership, the one thing you have to be careful of is that anything you put in a shared_ptr or a unique_ptr is really only owned by them.
In other words, what you are asking is "what objects does ROOT own?"
Unfortunately the answer is not very straightforward. Most of the knowledge you need is in the Object ownership section of the user’s guide.

I don’t have a general rule of thumb, but can probably reply to specific questions. File pointers returned by TFile::Open are yours. TTrees are owned by the directory (e.g. TFile) that contains them. Histograms are owned by the directory that contains them but you can “deregister” them from it calling SetDirectory(nullptr).

Hope this helps,

P.S. ROOT7 as well as modern ROOT interfaces (the ones in the ROOT:: namespace) use smart pointers all over the place, so it’s certainly possible, if not recommended to use them in user code as well.

1 Like