When should you declare variables as pointers, and when shouldn't you?

I’m trying to understand under what circumstances a variable should be declared as a pointer. For example, what would guide a programmer to choose between the following two ways of declaring a histogram?

TH1D *h = new TH1D("h","h",10,0,10);
TH1D h("h","h",10,0,10);

I understand the difference in how to use them, at least at a basic level (such as using -> vs .), but I don’t understand why I would choose one method of initialization over another.


Well, sadly with ROOT there’s a bit more to it:

Many ROOT 6 objects prefer heap allocation: new and pointers, due to ROOT’s traditional memory management (e.g. the file owning the histograms). We are moving away from that; all of ROOT’s new and future classes (RDataFrame, RHist, RCanvas, RNtuple etc) happily live on the stack!

Cheers, Axel.

Thank you, this is the context that I was looking for! Will ROOT’s old classes eventually be updated, or will they remain as they are?

This is great information, thank you.

We will not change the existing ROOT classes that fundamentally - most existing code would be broken if we change e.g. the ownership scheme for TH1.

@eggsAndCoffee given that this is relevant in general, would you be okay with moving this into the #root section?

Hi @Axel, yes I would be okay with moving this topic. Is that something that I can do, or do you need to do it?

Thanks, it’s now moved!

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.