Domanda

When I have a pointer to an object, how do I create a non-pointer variable from it?

My situation is this: I have a TFile class that loads files. These can contain various different named objects. TFile has a Get method (returning void*) that lets me retrieve one of those objects. What I usually do is:

TFile file("filename", "READ");
TTree* tree = (TTree*) file.Get("treename");

Now what I'd like to do is to be able to declare TTree tree as a non-pointer instead, and have it initialized from the returned pointer. Is there any way of doing this (preferably without copying the object, and without editing the source of TTree)?

È stato utile?

Soluzione

If you just want the syntax of a non-pointer object, use a reference:

TTree& tree = *static_cast<TTree*>(file.Get("treename"));

(Note that I replaced the C-style cast with a static_cast, which is not necessary, but usually considered good style.)

Note, however, that if you had to delete the TTree*, declaring it as a TTree& will not free you from this duty.

Altri suggerimenti

You can make a reference to the object, provided the lifetime of the object is sufficient:

Tree & tree = *static_cast<TTree*>(file.Get("treename"));

Be sure to check the documentation of TFile for a guarantee that the object lives at least as long as your tree variable.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top