In a subroutine, I create the following subroutine:
then fill it:
and then draw it:
However, I want to call this subroutine twice for different data, and hence in both cases create, fill and draw the histogram, with different data.
When I do it as above, the 2nd calling of the subroutine I get the warning:
Warning in TROOT::Append: Replacing existing TH1: h1 (Potential memory leak).
So, at the end of the subroutine, I call “delete h1”.
But now, it will delete the histograms as plotted on the canvas. (And I end up with nothing).
Another way, would be giving different names, according to the data that is called. Like this:
TH2D* h1 = 0;
if (first)
h1 = new TH2D("h1_1" , title.c_str(), 100, -2.0, 2.0, 100, -2.0, 2.0); // first time called
else
h1 = new TH2D("h1_2" , title.c_str(), 100, -2.0, 2.0, 100, -2.0, 2.0); // second time called
But of course, now, I will have to do the same when I fill and draw (if (first) h1_1->Fill(…) else h1_2->Fill(…)), and then there is no point in having one subroutine anymore. I might as well have two subroutines, doing exactly the same but with either h1_1 or h1_2. (Of course, this is fine, in this example, because I have only 1 histogram. But in real life, I actually have about 20 of them, so it really becomes ridiculous to have to copy the entire subroutine, just changing the histogram name).
If there would be something something like a “handle” for either h1_1 or h1_2, it would also help.
E.g.:
h1_handle = h1->GetHandle(); // would return either handle to h1_1 or to h1_2
h1_handle->Fill(...);
h1_handle->Draw();
But I could not find any method like that.
Maybe there is some really obvious way to solve this, but for the moment I have settled for the Memory Leak warning, which is annoying but at least it works. (If I could delete the histograms without deleting them on the canvasses, that would be fine too).
Best regards,
Machiel