Can I store std::shared_ptr to ROOT file?

Dear experts

Sorry if this is a duplicated question! I have two classes:

class A : public TObject{
//some parameters
};

class AContainer : public TObject, public std::vector<COMET::IDriftElectron*>{
//some mathods
};

Can I change the std::vector<COMET::IDriftElectron*> structure to std::vector<std::shared_ptr<COMET::IDriftElectron>>? Can I still store them into a ROOT TTree and TFile?


ROOT Version: 6.24.02
Platform: Linux
Compiler: gcc11


Hi,

The persistification of shared_ptrs, e.g. as data members, is not supported because of the semantic of the very class.
If I may, I would also discourage the design of classes inheriting from STL containers, and opt perhaps for encapsulation (this is a suggestion which is independent from ROOT).

Best,
Danilo

Thank you for answering! Could you please tell more that why it’s not suggested using STL containers?

You can and should use STL containers.

What is not recommended is designing a class inheriting from a STL containers (using composition is usually a better pattern).

You can find several writeups on the issue including Can We Inherit STL Containers? - GeeksforGeeks or https://www.researchgate.net/post/I-really-want-to-understand-if-there-is-any-reason-why-one-should-not-inherit-from-the-stl-vector-class-in-c

1 Like