Re: [ROOT] Memory management.

From: Rene Brun (Rene.Brun@cern.ch)
Date: Fri May 16 2003 - 15:07:21 MEST


Hi John,

A general rule;
 when the input arguments are basic arrays (eg TGraph(n,x,y)), the arrays
are copied into internally allocated arrays.
 When the input arguments are objects its is the same behaviour unless
specified otherwise in the documentation of the class.
In the case of TMultiGraph, the doc says:

//   A TMultiGraph is a collection of TGraph (or derived) objects
//   Use TMultiGraph::Add to add a new graph to the list.
//   The TMultiGraph owns the objects in the list.

I will add a few more comments to TMultiGraph::Add to clarify again what
is indicated in the header.
If you find other places where you think that it is unclear, let me know
and I will update the doc.

Rene Brun


John Pretz wrote:
> 
> Hello,
> 
> I have noticed that when you create a TGraph object, the TGraph will
> copy the array you gave it, so it is ok to delete the array after you
> create the TGraph.  When you make a TMultiGraph and start adding graphs to
> it, it is not ok to then delete the graphs.  Apparently
> TMultiGraph::Add(TGraph *) just saves away the pointer without copying it.
> 
> I was wondering if there is a general rule for when an object will make
> its own copy of something and when it will just use the copy you
> reference.
> 
> John
> 
> ************************************************************
> 
> Here's the code in case you're curious:
> {
>   int size = 1000000;
>   double *x = new double[size];
>   double *y = new double[size];
>   x[0]=0;
>   y[0]=0;
>   int i=0;
> 
>   for(i=0;i<size-1;i++){
>     x[i+1]=1.4-x[i]*x[i]+0.3*y[i];
>     y[i+1]=x[i];
>   }
> 
>   TGraph *gr1 = new TGraph(size,x,y);
>   TGraph *gr2 = new TGraph(size,y,x);
> 
>   delete x;
>   delete y;
>   //OK.  No segmentation violation if you use the graphs.
> 
>   TMultiGraph *mg = new TMultiGraph();
>   mg->Add(gr1);
>   mg->Add(gr2);
> 
> /*
>   delete gr1;
>   delete gr2;
> */
> //Doesn't work if these two lines are uncommented
> 
>   mg->Draw("AP");
> }
> 
> --



This archive was generated by hypermail 2b29 : Thu Jan 01 2004 - 17:50:11 MET