TTree::Branch() memory/adress safety

Dear all,

while writing an NTUPlizer, I stumbled upon a question regarding the safety/functioning of the TTree::Branch function.

When writing data to a TTree, e.g. a STL vector of doubles, now writes the following:

std::vector<Float_t> pt_;
myTree->Branch("pt"    ,  &pt_    );

and one then proceeds to loop over the events, stores the values in pt_, and calls the myTree::Fill() to store the data from the vector to the TTree. Now before the next event one needs to reset/clear the vector as to not mix up numbers of different events.

Because these calls of std::vector::clear() for each vector in the NTUPlizer can be easily forgotten and make for IMHO ugly code, I wanted to create a wrapper class dataContainer that contains all the vectors, i.e.

[code]class dataContainer {
std::vector<Float_t> pt_;

. The addition of the branches to the tree now look like this:
dataContainer dc_;
myTree->Branch(“pt” , &dc_.pt_ );
[/code] and instead of having to call the clear() function for all of the vectors, I just create a new dataContainer object for each event in the loop, i.e.:

Now I checked myself that this approach results in the same data being saved to the tree, but I am wondering whether the approach outlined above is save, i.e. it will never result in saving random/old bits of memory to the tree. I am worried because the address of the vector is only communicated once to the Tree in the Branch() call, but the address of the dataContainer Object and its member vectors could change when doing the reassignment at the beginning of the event loop.

Aside from the technical question, I’m wondering whether my approach is the “best” one, i.e. whether there are better solutions to avoid annoying and error-prone calls to vector::clear().

Sorry for the long post.



Since the object (dc_) does not move, dc_.pt_ does that move either, so your code is safe.

Personally, for the case you describe I would not use a wrapper class but just use:pt_.clear(); pt_.push_back(...); [...] and if you have more than one vector, i would use a wrapper class and the implement a simple clear function on the wrapper (this solution is somewhat more efficient cpu time wise)

Cheers ,