Re: [ROOT] Keeping histos visible without creating a memory leak

From: Rene Brun (Rene.Brun@cern.ch)
Date: Tue Oct 03 2000 - 19:07:22 MEST


Hi Suzanne,

Suzanne Panacek wrote:
> 
> Hi,
> The discussion on gROOT->Reset brought up another question.
> 
> When creating histograms on the stack in a named script, they disappear from
> the canvas because the destructor is called when the function exits.
> To prevent this, we create it on the heap instead. But, this creates a
> memory leak, because the variable is no longer available.
> 

This would be a huge leak ::)
When histograms and Trees are created, they are automatically added
to the list of objects in the current directory. You can get a pointer
to an histogram via statements like:
   TH1F *h = (TH1F*)gDirectory->Get("myHist");
or TH1F *h = (TH1F*)gDirectory->GetList()->FindObject("myHist");

where gDirectory (in TDirectory.h) is a pointer to the current directory.
This may be the current file(most of the time) or a subdirectory in a file.

When the file/directory containing the histogram(s) is closed, all histograms
are automatically deleted from memory.

You can remove an histogram from its parent directory by:
   h->SetDirectory(0)
or h->setDirectory(newdir)
In the first case, it is your responsability to delete the histogram.

If you are not happy with the default behaviour that automatically adds
the histogram to the current directory, you can call the static function:
   TH1::AddDirectory(kFALSE);
In this case, it is up to you to do the bookkeeping of all created histograms.

Suzanne, you can may be these comments at the pages 103,104 of the manual

Rene Brun



This archive was generated by hypermail 2b29 : Tue Jan 02 2001 - 11:50:34 MET