[Gc] Using GC in C++ via multiple inheritance

Basile Starynkevitch basile at starynkevitch.net
Fri Apr 12 22:52:05 PDT 2013

On Sat, Apr 13, 2013 at 10:42:27AM +0530, Shriramana Sharma wrote:
> Hello. I've been refactoring parts of Asymptote (asymptote.sf.net)
> code for inclusion into my own project and was hence introduced to GC.
> If I have to create MyClass as a subclass of a LibraryClass which
> doesn't use gc, is it sufficient for me to multiply inherit from gc
> and do:
> class MyClass : public LibraryClass, public gc {
> ...
> } ;
> so that new-ed instances of MyClass will be garbage collected
> including the LibraryClass sub-objects within them? I hope so, but I
> didn't want to assume, so am asking for this clarification here.

Yes, it is enough to do that. Look inside gc/gc_cpp.h header file. You see that
class gc only defines various operator new and operator delete.
So, no additional data is added to your MyClass, only additional behavior for new & delete.

Notice that MyClass will never be destroyed. So the GC would never call its destructor. In particular
the destructor of LibraryClass will not be called by the GC. If you want the GC to call destructors
declare insteead

   class MyClass : public LibraryClass, public gc_cleanup

You need to to so if for instance LibraryClass destructors do non-trivial things.

If you use STL containers like std::vector, you'll need also to use the allocator 
of gc/gc_allocator.h header, e.g. in C++2011 code something like

template <typename Elem_t>
using my_vector = std::vector<Elem_t,gc_allocator<Elem_t>>;

Then use later my_vector<MyClass>

Hope that helps.

Basile STARYNKEVITCH         http://starynkevitch.net/Basile/
email: basile<at>starynkevitch<dot>net mobile: +33 6 8501 2359
8, rue de la Faiencerie, 92340 Bourg La Reine, France
*** opinions {are only mines, sont seulement les miennes} ***

More information about the Gc mailing list