Important Object Ownership Management
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 | void ownership() { |
and
1 | void ownership() { |
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 | std::unique_ptr<TH1> hist; |
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.