[Gc] C++ API enhancement proposal

MenTaLguY mental at rydia.net
Sun Oct 14 08:35:11 PDT 2007


On Fri, 2007-05-11 at 08:48 +0200, Christophe Meessen wrote:
> 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.

Generally, in C++, instead of having a raw global object:

 Foo some_global(1, 2, 3);

...the best practice is to do something like this, using a global
accessor function instead:

 Foo &some_global() {
   static Foo *ptr=NULL;
   if (!ptr) {
     ptr = new Foo(1, 2, 3);
   }
   return *ptr;
 }

(In a multithreaded program, you must also add appropriate
synchronization to the accessor.)

The reason for this is that in any nontrival program there may be hidden
initialization dependencies between global objects.  Allocating them
on-demand means that (as long as there are no dependency cycles) objects
will automatically get initialized in the correct order.

Although this doesn't alleviate the need to call GC_INIT(), if you do
call GC_INIT() before using any global objects it will be safe if they
are initialized this way, versus being statically initialized.

-mental
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 189 bytes
Desc: This is a digitally signed message part
Url : http://napali.hpl.hp.com/pipermail/gc/attachments/20071014/76069d6d/attachment.pgp


More information about the Gc mailing list