Plot persistence depends of method of loading unrelated file

When I run the code below, it draws a histogram as expected. However, if TFile *f = ... is replaced with TFile f(...), the canvas is blank.

This only happens when run as a macro (root -l 'foo.c()'). When the exact same code is run in the interactive interpreter, the histogram shows as expected.

empty.root is an empty ROOT file.

Any ideas as to what causes this? I can’t see why declaring a file object on the stack vs. allocating it ought to affect the canvas.

void foo(void)
{
	TFile *f = new TFile("empty.root");
	//TFile f("empty.root");    // <-- problem

	TCanvas *c = new TCanvas("c", "c");
	TH1F *h2 = new TH1F("h2", "h2", 10, 0, 1);
	h2->Fill(0.5);
	h2->Fill(0.7);
	h2->Fill(0.3);
	h2->Fill(0.9);
	h2->Draw();
}

ROOT Version: 6.12/06
Platform: macOS 10.13.5


When you declare a variable on the stack, it is destroyed when it runs out of scope. In your case, the file is destroyed when you reach the end of foo(), and the same would be true for the canvas and histogram as well if you declared them on the stack.

Only the file is declared on the stack. The canvas and histogram are allocated with new and are entirely unrelated to the file.
When the file is allocated, the histogram draws and stays drawn after the macro exists. When the file is declared on the stack, the canvas is blank.

Yes, but the file becomes the associated directory for the canvas and the histogram.

I just tried on Mac with ROOT 6.15

I did:

root -l 'foo.C()'

or simply:

root -l foo.C

Using one of the three following ways to open the TFile works for me:

   auto f = new TFile("empty.root");

or

   TFile *f = new TFile("empty.root");

or

   TFile f("empty.root");   

Right after you create / open the file, execute:

gROOT->cd();

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.