TClonesArray and TObject containing a pointer to std::vector

I have the following class (I simplify)

[code]class Vertex : public TObject {
std::vector *_linkToAssociatedTracks;
Vertex() { _linkToAssociatedTracks = 0; }
~Vertex() { if (_linkToAssociatedTracks) delete _linkToAssociatedTracks; }
void AddTheLink (int theLink);

ClassDef(Vertex, 1);

void Vertex::AddTheLink (int theLink) {
if (!_linkToAssociatedTracks) _linkToAssociatedTracks = new std::vector;
if (_linkToAssociatedTracks) _linkToAssociatedTracks->push_back(theLink);

and I want to put it inside a TTree via a TClonesArray, so I can store multiple vertices within the same event (i.e. filling the tree event-wise).

I read somewhere that I should somehow define

Vertex::Clear() { if (_linkToAssociatedTracks) delete _linkToAssociatedTracks; }
and call

[code] // do the following once
TTree *tree;
TClonesArray *vertices;
vertices = new TClonesArray(“Vertex”, 20);
ntuple->Branch(“Vertex”, &vertices);

// do the following for each event
for (int i = 0; i < number_of_vertices; i++) {
new((*vertices)[i]) Vertex();
Vertex *thisVertex = (Vertex *)((*vertices)[i]);
for (int j = 0; j < number_of_tracks[i]; j++) {

Is this the correct approach? Actually the code crashes, so I’m not so confident about that.
Thank you in advance for your help!

This should work. However it is in contradiction with the goal of a TClonesArray. In your example you are going to add a tiny object in the array, but this object will do dynamic allocation, generating a lot of memory management and memory fragmentation. My advice is to rethink your object model such that you minimize this problem, fix the efficiency problem at the right time and not after using this type of construct in many places and fight later with timing and memory issues.
If the vector is short, say less than a few hundred, you will gain a lot in all aspects in declaring a fix length buffer inside the object in the TClonesArray, set to 0 the unused elements (they will be highly compressed on disk) and simply add one member indicating the current size of the array.
I know that in general computer scientists do not like my argument, but they are not the ones fighting later
on performance issues ::slight_smile:
For more details on TClonesArray, see the NOTE1 and 2 at