[Gc] C++ API enhancement proposal

Christophe Meessen meessen at cppm.in2p3.fr
Thu May 10 23:48:50 PDT 2007


I have seen by experience that one can easily forget to add the
GC_INIT() call in the main routine. But there is also a problem with
this call when used in C++.

In C++ one can allocate global variable with a user defined class type.
The class type may thus have a user defined constructor in which he may
do many interrestings things including allocating blocks. The problem is
that these allocations may be done priror to calling GC_INIT() because
global variable instantiation is done before calling main.

The solution is to add the following two lines of code to the gc_cpp.cpp
file. It declares a private object type with a constructor that simply
calls GC_INIT(). One simply add a global variable of this type in
gc_cpp.cpp so that GC_INIT will be called as soon as the library is
loaded and initialized. It should also work with dynamically loaded
libraries. I didn't test it though.

The other benefit is that C++ users won't have to add the GC_INIT() call
in the main function, a frequent source of problem.

add in gc_cpp.cpp

   struct GC_initializer { GC_init_struct() { GC_INIT(); } }
   GC_initializer gc_initializer;

Note: it won't completely eliminate the problem of global instance
initialization alloacting blocks because we can't ensure libgc is
initialized first. Better than nothing, in wait of gc support in C++.

More information about the Gc mailing list