No display when drawing graph

Hi, everyone.
I am facing a strange problem. Here is the structure of my code

std::pair<double,double> FindMin(TGraph *gr){
//Define a function to find a minimum of Graph
}
double FindDis(TGraph * gr){
//Define another function
}

void read(){
    TFile *f1 = TFile::Open("/Users/tianyu/InducedCharge/COMSOL/test/0p25_Noextend/test/Graph_0p8i.root","READ");
    TGraph *gr1 = (TGraph*)f1->Get("SeF5-");

    std::pair<double,double> min = FindMin(gr1);
        double x_p = min.first;
        double dis = FindDis(gr1);

    //create canvas and graph
    TCanvas c1("c1","",600,600);
    gr1->Draw();
}

After running the program, nothing displayed. Iā€™m sure that the functions I defined work well. The TCanvas seems not work. But when I tried to delete

TCanvas c1(ā€œc1ā€,ā€œā€,600,600);

and let root create canvas automatically, the graph could be displayed. There is no error or warning reported. Can someone shows some suggestions?
_

ROOT Version: 6.32.02
Platform: macosxarm64
Compiler: clang-1500.3.9.4


Hi,

Thanks for the post.

The problem is that the canvas is destroyed at the end of the scope of the function.
You can create a canvas as follows

auto c1 = new TCanvas("c1","",600,600);

Cheers,
Danilo

Hi @Danilo
Thanks for your reply. The problem was solved but I am still a bit confused. Each time when defining variable such as canvas, histogram, graph in a void function, the variables are always destroyed right? So is it necessary to use a pointer?

Hi,

Depends.

In C++, if an object is allocated on the stack, it is destroyed at the end of the scope. This is the case of your TCanvas in your initial snipped.

In C++, if an object is allocated on the heap (with new), it is not destroyed at the end of the scope. It needs an explicit delete.

ROOT objects, are registered internally, and are explicitly deleted automatically in some conditions or at the end of the program.

Cheers,
D

1 Like

Thanks :grinning: