I use root version 5.10 and I have a strange problem with TStrings. I declared a function that combines TStrings and returns the const char* TString::Data() member of the combined string. Occasionally, the output gets garbled. Here is the simplest version I could make of the problem (also attached) and below it is the output:
const Char_t* getName(Int_t n)
{
TString name = TString("h");
name += n;
return name.Data();
}; This can not work because the memory returned by name.Data() is held by the object ‘name’ and is freed when the function returns. As any already delete memory access, the behavior is random.
I figured that it was something like that. However, is there a simple solution to get this to work? Basically, what I use is a more complicated version that involves a lot more input parameters. I do this to give every object that I name a unique name based upon the set of parameters that I feed it. Each object can then be accessed on a TClonesArray through the FindObject() method. It seems as though this should be possible, and easy.
Thanks, I had already started doing that. I wanted to avoid having to to do getName().Data() everytime I wanted the name, but it looks like I have to return the TString instead of a const char*. Oh, well.
Alternatively you can replace you getName(n).getData();byForm("h%d",n);.
Also note that in most case (except variadic function like printf), you can use the TString where a const char* is expected.