No ability to copy TGraph2DErrors

Hello,

I am having difficulty copying a TGraph2DErrors using its inherited Clone method. The trouble is when I write code like this.

TGraph2DErrors* GetGraphFromFile(TString file_name)
{
     TGraph2DErrors *gr = 0;
     TFile *f = new TFile(file_name.Data());
     gr = dynamic_cast<TGraph2DErrors*>(f->Get("mygraph"));
     if (gr!=0)
     {
           TGraph2DErrors* temp_gr  =  dynamic_cast<TGraph2DErrors*>(gr->Clone("temp_gr"));
           gr = temp_gr;
     }     
     f->Close();
     return gr;
}

The result of the above returns a non-null ptr to my TGraph2DErrors object, but it now contains null data pointers fX, fY, …, and fEZ that cause segmentation faults. It appears that the TFile is claiming ownership over the TGraph2DErrors as it would a histogram or ttree. Can this be? If so how do I copy/clone the object for later use?

I have attached a more detailed example to demonstrate.
example.root (265 KB)
tgraph2derrors_copy_problem.cpp (1.82 KB)

Instead of:
gr = dynamic_cast<TGraph2DErrors*>(f->Get(“mygraph”));
use:
f->GetObject(“mygraph”, gr);
See http://root.cern.ch/root/html/TDirectoryFile.html#TDirectoryFile:Get

Try this:

gROOT->cd(); TGraph2DErrors *temp_gr = ((TGraph2DErrors*)(gr->Clone("temp_gr")));
Note that TGraph and TGraph2D are very different. TGraph2D is more akin to a histogram.
See also [url]Moving TGraph to a new file and [url]Object ownership by TFile and http://root.cern.ch/download/doc/8ObjectOwnership.pdf

I get the same result. See the implementation of your workaround in the attached example.
tgraph2derrors_copy_problem.cpp (1.86 KB)
myfile.root (265 KB)

Ah I forgot the gROOT->cd()… the workaround worked. Thanks.

You did NOT add “gROOT->cd();”
Well, now you did :mrgreen:

Incidentally, the gROOT->cd() is the only piece that was missing in the original code.

Now that I understand this is more TH2-like, I have realized that another solution to the problem would be to add a

temp_gr->SetDirectory(0)

Thanks again.