Draw TLine inside a function


TLine l(0.,0.,5.,5.); l.Draw();

void f(){ TLine l(0.,0.,5.,5.); l.Draw(); } f();
does not. Why?

The TLine is a local variable that goes out of scope after the function ends. If you wish to draw graphical objects that persist after the end of a function, you have to let its memory leak out, like so:

void f()
  TLine * l = new TLine(0.,0.,5.,5.);

You can see more examples from my code here where I draw circles and text labels and such:

Of course you have to be careful to only do this so much (or make sure your programs are short), because this is a purposeful memory leak. The way to avoid the memory leak is to build a container of all the graphical objects and return it from the function, making sure to grab it on the other side of the function call. Since I rarely want to make more than tens of graphs, I just do the memory-leaky way since it’s easier.



Maybe one more question, when a TLatex object is drawn and later goes out of scope, it’s still on the canvas. How do I know which objects need to persist to be seen on the canvas?

Turns out I was wrong about it depending on TNamed and such, please ignore if you read my earlier un-edited post. Leaking memory still works though.


jfcaron’s reckoning about TNamed seems false to me based on

[li]Experience: Try e.g. TF1 which inherits TNamed.[/li]
[li]Language rules: At least for compiled programs, if local object goes out of scope, it will be destroyed. I don’t know what ROOT actual does, but I would be very surprised if it somehow copied the local objects in to the global memory of ROOT.[/li][/ul]

One way to handle the memory is to pass ownership to pad, see documentation of kCanDelete (“If you want TCanvas to delete the primitive you created you have to set the kCanDelete bit”).

Does the TLatex remain on the screen even after you update the screen e.g. by resizing the window?

Yes it does.

I can’t confirm the observation about TLatex: it will disappear if it goes out of scope just like others. However if you used DrawLatex() function, that will, as documented, create a copy that is owned by the pad and that would explain why the text won’t disappear.