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();
}
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.