TObject Clone versus stl copy

Hi all,

I want to copy some data taken from TTrees using SetBranchAddress, then pass that pointer to a new data object. Then I want to copy that data into the new object. Is it better to use TObject::Clone or simply use stl’s copy from algorithm? Or does it matter? Here’s a little pseudo code of what I mean.

TMyData *data = new TMyData();
tree->SetBranchAddress("data", &data);
TSuperClass *sc = new TSuperClass(data);

Now I want to copy the data into the new class so that I don’t follow with things that happen in the TTree class.

Does it matter if I do use

TSuperClass(TMyData *data){
  fData = data->Clone()
  // or
  fData = new TMyData();
  std::copy(fData, data, data+1);

I don’t know a ton about the TObject::Clone() function, but it does seem to allocate memory. Is there anything about ROOT that would make it important to use the Clone() function?

In general, in ROOT classes I like to stay consistent with other ROOT classes and functions. But, I don’t really like using Clone without really knowing what’s going on.



[quote]std::copy(fData, data, data+1);[/quote]Why even use std::copy? Isn’t this exactly the same as *fData = *data;?

TObject::Clone write the input object into a memory buffer using the Streamer and then create a new object and read the data back from the memory buffer.

In your simple case, you should just write a proper C++ copy constructor in your class and do:TSuperClass(TMyData *data){ fData = new TMyData(*data); }



Yeah, your right! Thanks.

I don’t know why I was thinking that. I have kind of a habit of using std::copy, just because it’s safe, but obviously not needed here.


I don’t know why I was thinking that. I have kind of a habit of using std::copy, just because it’s safe …

Hmmmm, if we look at your code sample:

std::copy(fData, data, data+1);

and the declaration of copy:

template<class InputIterator, class OutputIterator>
OutputIterator copy(InputIterator first, InputIterator last,
OutputIterator result);

Are you still sure, it’s safe for you? :wink:

Oh, whoops…