ROOT Manual - Basics: Object Ownership Question


Please read tips for efficient and successful posting and posting code

ROOT Version: Not Provided
Platform: Not Provided
Compiler: Not Provided


The following snippets are adapted from the Manual.
I created an empty file.root and ran the following.

void ownership() {
  TFile myFile("file.root"); 
  TH1F * h1 = new TH1F("h1","Histogram from a Gaussian",100,-3,3);
  h1->FillRandom("gaus",10000);
  h1->Draw();
}

I saw a blank canvas as promised. My guess is that h1 automatically got owned by myFile, so at the end of the scope h1 was deleted. Cool.

What I am curious about is the ownership of h1 if I created it on the stack

void ownership() {
  TFile myFile("file.root");
  TH1F h1("h1","Histogram from a Gaussian",100,-3,3);
  h1.FillRandom("gaus",10000);
  h1.Draw();
}

My questions are:

  1. Who owns h1 in this case?
  2. I still see a blank canvas, but is that because h1 “owns itself” (I actually dunno what I’m talking about here, please forgive the ignorance) and goes out of scope when we reach }, or because h1 still gets automatically owned by myFile when we reach }?

but is that because h1 “owns itself”

Close enough :). It is because h1 is created on the stack and thus is destructed at the end of the function.

My guess is that h1 automatically got owned by myFile, so at the end of the scope h1 was deleted

Correct.

To solve your issue, take ownership of the histogram with:

void ownership() {
  TFile myFile("file.root"); 
  TH1F * h1 = new TH1F("h1","Histogram from a Gaussian",100,-3,3);
  h1->FillRandom("gaus",10000);
  h1->Draw();
  h1->SetDirectory(nullptr);
}

Although in this case the histogram is leaked. So you may need something like:

std::unique_ptr<TH1F> ownership() {
  TFile myFile("file.root"); 
  TH1F * h1 = new TH1F("h1","Histogram from a Gaussian",100,-3,3);
  h1->FillRandom("gaus",10000);
  h1->Draw();
  h1->SetDirectory(nullptr);
  return h1;
}
1 Like

Thanks!
I guess I don’t really know what is meant by ownership here.
Does it make sense to talk about ownership when it comes to something created on the stack?
As in, if h is created on the stack, can it be owned by anyone?

In this case you can think of the local ‘stack’ or ‘scope’ as owning the object.

Following page 10 of some slides online, I tested the following, which seg faults

void ownership() {
  TFile myFile("file.root", "RECREATE"); 
  std::unique_ptr<TH1F> h1(new TH1F("h3","Histogram from a Gaussian",100,-3,3));
  myFile.Close();
  h1->FillRandom("gaus",10000);
  h1->Draw();
}

and this creates a blank canvas as expected

void ownership() {
  TFile myFile("file.root", "RECREATE"); 
  TH1F h1("h3","Histogram from a Gaussian",100,-3,3);
  myFile.Close();
  h1.FillRandom("gaus",10000);
  h1.Draw();
}

Am I correct to assume that even with unique_ptrs ROOT will take ownership of histograms, but not if the histogram is on the stack?

Correct.

1 Like