// Include file for GC-aware allocators. // alloc allocates uncollected objects that are scanned by the collector // for pointers to collectable objects. Gc_alloc allocates objects that // are both collectable and traced. Single_client_alloc and // single_client_gc_alloc do the same, but are not thread-safe even // if the collector is compiled to be thread-safe. They also try to // do more of the allocation in-line. #include "gc_alloc.h" // Redefine global operator new and delete to get garbage collected // memory. This isn't necessary to use gc_alloc with STL containers. // But a program that does all of its allocation through STL containers // currently doesn't benefit much from garbage collection anyway. #include "gc.h" inline void * operator new(size_t n) { return GC_malloc(n); } inline void operator delete(void *) {} inline void * operator new[](size_t n) { return GC_malloc(n); } inline void operator delete[](void *) {} #include #include #include // The SGI rope package omits reference counting if __GC is defined. // Since reference counts are also used for other purposes, this // doesn't always win. #define __GC #include // Short name for allocator. typedef gc_alloc all; // Comparison on C strings. inline bool compare(char *x, char *y) { return (strcmp(x,y) < 0); } main() { rope msg("All done!"); for (int i = 0; i < 1000; ++i) { // Vector in garbage-collectable memory. vector a(1000); char *first; for (int j = 0; j < 1000; ++j) { // Fill in array. It is now safe to share array elements, // or have some of them allocated statically and others // dynamically. Plain C strings work fine here. // The dynamically allocated entries and // the vector itself will be garbage collected. if (j % 3 == 0) { a[j] = new char[3]; strcpy(a[j], "de"); } else if (j % 5 == 1) { a[j] = a[j-1]; } else { a[j] = "abc"; } } sort(a.begin(), a.end(), compare); first = a[0]; assert(first[0] == 'a'); } cout << msg << endl; }