The attached macro “macroTestCopy.C” shows my problems:
1, Why do methods CopyProjectInfo2() and CopyProjectInfo3() not work?
“.x macroTestCopy.C+” does not print ProjectC and ProjectD, while
“.x macroTestCopy.C” crashes.
2, Why does function TestCopy1() not work?
3, In my real program I need to copy objects, which are created on
the heap (as shown in function TestCopy1()):
What do I need to do to copy an object created on the heap?
Thank you in advance for your help.
Best regards
Christian macroTestCopy.C (8.64 KB)
Your program will work if you fix a bug in your code in
MyClass::CopyProjectInfo3
You are adding to a TList a local object XprojectInfo that is destroyed
when leaving the function. As a result you have a pointer to a dead object
in the TList
XProjectInfo *infocopy = new XProjectInfo();
infocopy->Copy(info);
fList->Add(infocopy);
but you also have
// XProjectInfo *infocopy = new XProjectInfo();
XProjectInfo infocopy;
info->Copy(infocopy);
fList->Add(&infocopy);
I think that the second should be
XProjectInfo *infocopy = new XProjectInfo();
infocopy->Copy(info);
fList->Add(&infocopy);
I.e. fix both the memory error and the copy direction error.
Also this can not work in interpreted mode since you class derived from a compiled class AND overload a virtual function.