[Gc] Newbie Question

Simon Gornall simon@gornall.net
09 Feb 2003 11:15:12 +0000


Hi there,

I'm trying to port across a Java program to C++, to make it run a lot
faster, and I thought at the same time, using an automatic
garbage-collection library might solve some problems... 

Basically I want some of the collection classes, (Vector, Hashtable,
etc.) and some of the basic classes (String, Integer, etc.) and not much
else. What is slightly confusing me is the use of explicit cleanup
functions.

Assuming I implement Vector or Hashtable, I'm going to end up with
arrays of collectable classes, and so I'll have to 'new' them with a
specified cleanup function, yes ?

So, I looked at the tests/test_cpp.cc (specifically, class D seemed to
look a reasonable model) but inside CleanIp() I don't see how 'D* self'
is being freed. Also, I'm not sure what the assert is doing "(int)(long)
?".

The only reason I can think that 'D* self' is being freed is that the
declaration causes the collector to reap it at the closing brace - is
this the case ? So if I have an array of objects in a class extending
gc_cleanup, just by creating a reference to the memory, the collector
will free the objects ?

eg:

class A : public gc_cleanup
   {
   A::CleanUp(void *obj, void *data)
      {
      A* self = (A*) obj;

      for(int i=0; i<self->length(); i++)
         {
         // referencing each object will delete it ?
         JavaObject *obj = (JavaObject *) self->get(i);
         }
      }
   }

... but then in that case, why not just put it into the destructor of
the collection object ?

class A : public gc 
   {
   A::~A 
      {
      for(int i=0; i< _arraySize; i++)
         {
         // referencing each object will delete it ?
         JavaObject *obj = (JavaObject *) _array[i];
         }
      }
   }

This must be something that everyone who deals with C++ arrays has come
across, and I get the feeling I'm missing something fundamental - any
enlightenment would be very useful :-)

ATB,
	Simon.