Dear Experts,
I have a question about the proper method for writing a ROOT compatible class to a TFile. In particular, for a class containing a pointer which it may or may not own. A basic example of the code is below.
A class MyClass has a member variable MyClass::fPointedClass which is a pointer to MyPointedClass. Depending on the use case, MyClass is either responsible for deleting MyClass::fPointedClass or not. This is achieved in the constructor, where a MyPointedClass pointer is passed as an optional argument. If a MyPointedClass pointer is passed, MyClass just refers to the external copy, and sets a variable MyClass::fOwnPointed = kFALSE. Otherwise, MyClass constructs its own MyPointedClass, and sets the variable MyClass::fOwnPointed = kTRUE. When the destructor is called, MyClass::fPointedClass is only deleted if MyClass::fOwnPointed == kTRUE.
My question is how to treat this when using MyClass::Write() to save MyClass to a TFile. Because MyClass::fPointedClass generally isn’t needed after reading MyClass from a file (in the usual use cases) I just need something that doesn’t break. For example, after reading a MyClass from a TFile, the MyClass::fPointedClass doesn’t necessarily point to something, but MyClass::fOwnPointed can be kTRUE, which causes problems for the copy constructor etc.
The simplest behavior seems to be having MyClass::fOwnPointed always be kTRUE, and save a separate copy of MyClass::fPointedClass saved for each MyClass, or a new one made each time. Perhaps using “//!” so that the two class variables (MyClass::fOwnPointed and MyClass::fPointedClass) aren’t included by the streamer, and then initializing them in the default constructor? I don’t know if this works with the current ROOT I/O setup though; any suggestions on the best way to accomplish this would be welcomed.
I’m also curious if I can get the correct behavior for MyClass::Clone(). In the case that MyClass::fOwnPointed is kFALSE, it works fine. However, for MyClass::fOwnPointed == kTRUE, a new MyClass::fPointedClass isn’t created for the cloned object. Any suggestions on how to accomplish this?
Thanks a lot for your help!
Chris
#include "TNamed.h"
class MyPointedClass : public TNamed {
MyPointedClass(const char *name, const char *title) : TNamed(name, title) { }
MyPointedClass() : TNamed() { }
virtual ~MyPointedClass() { }
ClassDef(MyPointedClass, 1);
}
class MyPointedClass : public TNamed {
private:
MyPointedClass *fPointedClass;
Bool_t fOwnPointed;
public:
MyClass(const char *name, const char *title, MyPointedClass *pointed = NULL) : TNamed(name, title) {
if (pointed) {
fPointedClass = pointed;
fOwnPointed = kFALSE;
} else {
fPointedClass = new MyPointedClass("pointed", "pointed");
fOwnPointed = kTRUE;
}
}
MyClass() : TNamed(), fPointedClass(NULL), fOwnPointed(kFALSE) { }
virtual ~MyClass() {
if (fOwnPointed) delete fPointedClass;
}
ClassDef(MyClass, 1);
}