Topic: Garbage collection (was Re:what's allocator?)
Author: Michiel Salters <salters@lucent.com>
Date: 2000/04/04 Raw View
Niklas Pettersson wrote:
> Can you implement a garbage collector for C++ using alloctators?
In the Java sense, no.
Allocators have no way of knowing what pointers/references exist
soemwhere in user code. Therefore they can't free up allocated
objects.
However, the containers using your allocator will indicate
when they've finished using the memory, and that will tell the
allocator when it can free up memory. So it can be considered
a pretty dumb "garbage collector".
The closest thing to garbage collection in C++ is the smart
pointer concept. In particular, for non-circular references
www.boost.org boosts a counted ptr. I'm not sure if it can
be used as the base of a true garbage collector.
I.e. given
struct L;
struct L
{
garbage_collecting_ptr<L*> buddy;
L():buddy(0);
explicit L(L* other): buddy(other);
setbuddy(L* other) { buddy=other;}
}
void f() {
garbage_collecting_ptr<L*> *single_link;
single_link = new L; // A object
single_link.setbuddy(new L(single_link)); // B object
} // single_link is deleted here.
How should garbage_collecting_ptr<> be written so that the
deletion of single_link will take out both objects, or for
that matter any object that becomes unreachable(*) at the
destruction of a garbage_collecting_ptr?
(*) unreachable would be defined as not reachable through
garbage_collecting_ptr's. An intermediate goal would be to
define unreachabel as not reachable through
garbage_collecting_ptr<L*>, i.e. only delete homegenous
sets of objects.
Michiel Salters
---
[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:std-c++@ncar.ucar.edu ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://reality.sgi.com/austern_mti/std-c++/faq.html ]