[gclist] boehm-gc and the STL

David Jones dej@inode.org
Tue, 6 May 2003 12:19:01 -0400


I have just started playing with the Boehm collector under C++ and have run
into a problem with STL objects.  Strangely, my question doesn't seem to have
been asked before, either here, in the GC FAQ, or in the boehm-gc
documentation.

The basic problem is: by default, memory allocated by an STL container is done
using the default operator new, and is uncollectible.  Furthermore, this
memory does not appear to be scanned for pointers, so if the only reference
to an object is in an STL container, then it is likely to be freed
prematurely.

The "gc_cpp.h" include file has this to say:

  Collectable objects may freely point at uncollectable objects and vice
  versa.

  Objects allocated with the built-in "::operator new" are uncollectable.

I would interpret this to mean that the STL scenario ought not to be a
problem.  However, the "debugging.html" file in the boehm-gc documentation
has this to say:

    2. The last pointer to an object in the garbage collected heap was
       stored somewhere were the collector couldn't see it, e.g. in an
       object allocated with system malloc...

On FreeBSD with GCC3.2.2, the default C++ operator new uses system malloc (I
think).

It seems to me that these files are in conflict, unless I am reading too much
into "freely point".

How to deal with this?  I see two main ways:

1. Write an allocator for STL objects that uses GC_malloc.  Drawback: since
   C++ doesn't have "template typedefs", you need to write an ugly template
   instantiation each time you want to use a container, e.g.:

   typedef std::vector<MyObject*,STL_GC_allocator<MyObject> > MyVector;

2. Write a default operator new to use GC_malloc.  Drawback: this is
   suboptimal if you use third-party libraries whose memory management
   is OK, as you have to scan their allocations, but again what to do
   if the only pointer to your object is in the third-party data
   structure?

How do people in the real world solve this problem?  Are there any other
pitfalls?