Re: [ROOT] Little hint about pointers

From: Christian Holm Christensen (cholm@hehi03.nbi.dk)
Date: Tue Nov 20 2001 - 15:20:32 MET


Hi Alberto, 

On Tue, 20 Nov 2001 13:11:29 +0100
Alberto Pulvirenti <alberto.pulvirenti@ct.infn.it> wrote
concerning "[ROOT] Little hint about pointers":
> Dear all (but maybe it's Rene who knows the answer)
> 
> I've a little question about dynamic memory allocation. Follow this 
> example to understand what the question is.
> 
> I have two classes, say 'C1' and 'C2', inheriting from TObject. In 
> particular, in the C2 is defined a data-member which points to a C1 object:
> 
> class C2 : public TObject {
> 
>   .
>   .
>   .
> 
> public:
> 
>   .
>   .
>   .
> 
>   C1 *fPointer;
> 
>   .
>   .
>   .
> 
> };
> 
> 
> In my work, I have created a TObjArray, say obj_arr, where I stored many 
> objects of class C1. When I create a C2 object, I initialize its 
> fPointer data-member to point to one of the elements of the 'obj_arr' 
> collection:
> 
> C2 *c = new C2;
> c->fPointer = (C1*)obj_arr->At(k);
> 
> However, I need to delete the C2 object, without deleting the C1 object 
> it points to. Then, what must I put in the C2 destructor?
> 
> If I use this one:
> 
> C2::~C2() {
>    delete fPointer;
> }
> 
> will it erase the memory, cancelling the C1 object even if I keep in RAM 
> the TObjArray where it was initially stored?

Yes. 

> Or this will remove only the link, but, given that there is another 
> class which points to that memory slot (obj_arr, in this case), the C1 
> object will be kept and not deleted?

Yes and no.  The link exists in th obj_arr, but it points to
deallocated memory, and you're likely to get a SIGSEGV if you try
access it.   

> The question comes from the observation I did that, without using the 
> destructor I presented you, it seems to come a large memory leak, so I 
> thought it was necessary to use it...

If you send the message TObjArray::Delete, it will delete all objects
pointed to by the array, so that's what you need to do. 

> If I was clear, could you give me a hint about this question?

See the attached code.  See also chapter 8 in the Users Guide (Yeps,
RTM). 
 
Yours, 

Christian Holm Christensen -------------------------------------------
Address: Sankt Hansgade 23, 1. th.           Phone:  (+45) 35 35 96 91 
         DK-2200 Copenhagen N                Cell:   (+45) 28 82 16 23
         Denmark                             Office: (+45) 353  25 305 
Email:   cholm@nbi.dk                        Web:    www.nbi.dk/~cholm






This archive was generated by hypermail 2b29 : Tue Jan 01 2002 - 17:51:09 MET