Draw TLine inside a function

Hi

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

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

You can see more examples from my code here where I draw circles and text labels and such:
http://bazaar.launchpad.net/~jfcaron/+junk/Proto2BeamTest2/view/head:/JFTrackFit.C#L373

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.

Jean-François

Thanks!

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.

Jean-François

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

[ul]
[li]documentation[/li]
[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.