Copying TH1F

Hey people,

I open a root file, get a pointer to a histogram outof it via:

TH1F* h1 = (TH1F*)myfile->Get(name);

Then I make a copy of h1 via the TH1F::Clone() function

TH1F* copy_of_h1 = (TH1F*)h1->Clone();
copy_of_h1->SetName(“mycopy”);

and close the file again. I’m aware that h1 should be gone at this time,
but it seems that copy_of_h1 is also not available any more. If I want to
access it e.g. in the following way:

if(copy_of_h1)
{
copy_of_h1->GetName();
}

the program crashes with segmentation violation. It seems that the pointer
of copy_of_h1 is still there but it’s not pointing any more to anything useful.

I also tried to use the Copy function and the copy constructor like this:

TH1F* copy_of_h1 = new TH1F( *h1 );

or

TH1* copy_of_h1 = new TH1F();
h1->Copy(*copy_of_h1);

all with the same result.
I want to keep the copy even if the file where it originally came from is closed.
How can I get this?

Many greetings
Roger Wolf

Hi Roger,
see ch 8 of the users guide, p107. TH1::SetDirectory or AddDirectory(kFALSE).
Axel.

In addition to Axel’s answer, note that when you Clone an object,
you can also set its name, eg
TH1F* copy_of_h1 = (TH1F*)h1->Clone(“mycopy”);

Rene

many thanx! this was exactely what I was looking for… :open_mouth: