Save class with reference to a container element

I’d need to understand what happens in the following situation:

  • class A has a member which is a raw pointer to an object of class B;
  • object a of class A has this member pointing to vb[i], where vb is a std::vector<B> (or another STL container` ;
  • both a and vb are saved in a Root tree in two different branches of the same tree.

My question is: is vb[i] written twice in the Root file, or is Root capable of detecting that the reference in a is pointing to an element of vb which is being written on file as well, and thus optimize the disk write by writing vb[i] just once?
Thanks.

class A has a member which is a raw pointer to an object of class B;

Because it is a raw pointer the default is to assume A owns the pointee.

My question is: is vb[i] written twice in the Root file,

It depends on 2 things.

  • whether the the pointer and the vector are stored in the same I/O operation (in the same TKey or TBasket)
  • where the vector is stored before the pointer.

If the vector is stored fist and the pointer is stored in the same I/O operation, the system will notice the pointer is a second sighting and record it as a reference.

If the vector is stored second (i.e. when unfolding the object hierarchy depth first, it is listed later than the pointer) OR if it is stored in a different I/O operation (for example, your case, if they are stored in different branch) then

* the pointee will be stored twice
* upon reading the connection between the pointer and the vector will be gone (there will be 2 distinct objects).

So the best solution for your case is to replace the pointer (or add but make the pointer ‘transient’) with an index (an integer) that is use to look-up the object in the vector.

Cheers,
Philippe.

PS. There is an alternative if you B inherits from TObject, which is to replace the pointer by a TRef and to call TTree::BranchRef to enable reference tracking.

Thanks Philippe. Unfortunately I cannot use an index since the vector migth or might not be saved depending on user’s choice, and indeed my question was mainly to understand if I would get an object duplication in case the user decides to save the vector. But I’d say this is the price to pay for this flexibility.

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