TClonesArray of TParticle Derived Class: ExpandCreate

Hi Rooters,

I developed a very simple class inheriting from the TParticle, called KAParticle.
I want to store many KAParticle objects in some TClonesArray instances, in a loop, like in the dummy example I paste here:

[code]#include “TClonesArray.h”
#include “KAParticle.h”

int main(){

int nloops=100000000;
int nallocations=1000;
TClonesArray* v=new TClonesArray("KAParticle");
for (int i=0;i<nloops;++i){
    if(i%2 == 0)
        nallocations/=2;
    else
        nallocations*=2;
    v->ExpandCreate(nallocations);
    for (int j=0;j<nallocations;++j){
        KAParticle p;
        new ((*v)[j]) KAParticle(p);
        }

    }

}
[/code]
A huge leak is generated: the KAParticle destructor is not enough. Which function should I implement in the KAParticle class to prevent such behaviour?

Cheers,
Danilo

Hi Danilo,

You need to implement KAParticle::Clear() which must delete the memory allocated in the constructor and reset the pointer value to zero (to avoid potential double delete.

And then you need to callv->Clear("C");at the end of the loop.

Note that to allocate the object the following is sufficient:new ((*v)[j]) KAParticle();

Cheers,
Philippe.

Hi Fons,

thanks for the quick reply.

I implemented the Clear() method and the leak disappeared.

Thanks for the hint!

D

PS
You are also right about the allocation. The copy ctor was due to some “history”…