An object ownership means the permission to delete it.
Modern code should use local variables or
std::unique_ptr; but some of ROOT’s types are managed differently.
To prevent memory leaks and multiple attempts to delete an object, you need to know which objects are owned by ROOT and which are owned by you.
By the end of this page you will know why
shows an empty canvas after calling
Ownership by current directory
Changing the directory of a histogram (same applies to trees and event lists):
You can remove a histogram from a directory by using
SetDirectory(nullptr). Once a histogram is removed from the directory, it will not be deleted when the directory is deleted. Instead, you have to delete the histogram yourself to prevent memory leaks.
Disabling ROOT’s automatic ownership management for histograms
To prevent histograms from being added to the current directory, call the static function
Now you own all histogram objects and you will need to delete them, for instance through the use of
You can still set the directory of a histogram by calling
SetDirectory() once it has been created.
When you create a
object, it becomes the current directory (
If you subsequently create a new histogram, this histogram is now owned by the current directory:
the histogram is deleted when the
Finally, this canvas shows the histogram because it is owned by a
unique_ptr which lives longer than the function
gROOT object has several utility collections, for instance of all functions
gROOT->GetListOfCanvases(), and files
Objects that are members of these collections and are still “alive” during program tear-down are deleted by
If they get deleted earlier, they de-register themselves from
TROOT’s lists (“recursive remove”) to prevent double deletions.
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.
The call of
Fit() copies the global
Gaussian function and attaches the copy to the histogram. When the histogram is deleted, the copy is deleted too.