Important Object Ownership Management

Albert Cheung

General

ROOT will help you manage some objects, but others should be managed by yourself. When a histogram, a TTree or a TEventList is created, it is added by default to the list of objects in the current directory gDirectory. In many cases that is the TFile that was opened most recently.

You can use

1
h -> SetDirectory(newDir);

to change the directory of a histogram. If you change that new directory newDir to nullptr, then the histogram will be removed from the directory, and the histogram will not be deleted if you delete the directory. In this case, you must delete this histogram to avoid memory leak!

Example

Here is an example, two cases:

1
2
3
4
5
6
7
void ownership() {
TFile file("file.root");
auto hist = new TH1F("hist", "hist", 10, 0., 1.);
hist->Draw();
// At the end of the function, `file` is destructed.
// The destructor `~TFile` deletes `hist`: no histogram is left.
}

and

1
2
3
4
5
void ownership() {
auto hist = new TH1F("hist", "hist", 10, 0., 1.);
TFile file("file.root");
hist->Draw();
}

Only the second case shows correct histogram. That’s, if you subsequently create a new histogram, this histogram is now owned by the current directory: the histogram is deleted when the TFile object destructed. The first one, TF1 owns the TH1F, so it shows nothing. But the second one, the canvas shows the histogram because the TH1F histogram is created before the TFile is opened; the TFile does not own it.

1
2
3
4
5
6
7
8
9
std::unique_ptr<TH1> hist;
void ownership() {
TH1::AddDirectory(false);
TFile file("file.root");
hist.reset(new TH1F("hist", "hist", 10, 0., 1.));
// or, instead of TH1::AddDirectory(false):
// hist->SetDirectory(nullptr);
hist->Draw();
}

This code uses std::unique_ptr to manage object, this can insure the histogram still exist after the ending of the function.

Ownership by Creating Objects

When an object creates another, the creating object is often the owner of the created one. This will be documented in the function creating the other object. For example:

1
myHisto->Fit("gaus")

The call of Fit() copies the global TF1 Gaussian function and attaches the copy to the histogram. When the histogram is deleted, the copy is deleted too.

  • Title: Important Object Ownership Management
  • Author: Albert Cheung
  • Created at : 2024-10-19 19:31:52
  • Updated at : 2024-10-19 20:22:54
  • Link: https://www.albertc9.github.io/2024/10/19/object-ownership/
  • License: This work is licensed under CC BY-NC-SA 4.0.
On this page
Important Object Ownership Management