[Gc] Using C++ Standard Template Library with GC.

Fred Gylys-Colwell fredgc@member.ams.org
Wed, 29 Oct 2003 22:13:07 -0800


Hello.

Does anyone have an example of using the garbage collector with the
STL containers?  I have read the documentation in gcinterface.html
and am still confused.  In particular, I have an example where I put
several gc_cleanup objects into a container, and find that they are
being prematurely collected.

I am using GC 6.3alpha2, on Linux (2.4.22), with gcc 3.2.2.  

If you can give me some pointers on fixing my example, I would be
very happy.  A working example would be even better!

Thanks,
	Fred GC.



------------------------------ cut here ------------------------------
/* This is a test of the Boehm-Demers garbage collector.
   It tries to combine some STL containers with gc objects.

 */

#define GC_LINUX_THREADS 

#include <pthread.h>

extern "C" {
#include<gc.h>
}
#include<gc_cpp.h>
#include<gc_allocator.h>

#include <iostream>
#include <map>
#include <string>

using namespace std;

#define UU __attribute__ ((unused))

bool running = true;

class A : public gc_cleanup {
  public:
    int buffer[1000];
    string s;
    A(string n) : s(n) {
    }
    ~A() {
	if( running ) {
	    cout << "Warning: A("<< s<<") should not be deleted.\n";
	}
    }
};

class B : public gc_cleanup {
  public:
    map<string,A *> table;
    int buffer[1000];
    B() {
  	string s = "index_";
  	for(char  c = 'A'; c <= 'Z'; c++) {
  	    table[s+c] = new A(s+c);
  	}
	table["one"] = new A("one");
	table["two"] = new A("two");
	table["three"] = new A("three");
	cout << "Finished creating B.\n"; 
    }

    ~B() {
	cout << "Deleting B.\n";
    }
};


int main() {
    cout << "sample11\n";
    running = true;
    B *object UU = new B();
    cout << "Created new object.\n";
    GC_gcollect();
    cout << "After GC_gcollect\n";

    cout << "object = " << object << "\n";
    cout << "reference still exists: object->table[one] = "
	 << object->table["one"] << "\n";

    running  = false;
    return(0);
}

------------------------------ cut here ------------------------------









-- 
----------------------------------------------------------------------
	    Fred Gylys-Colwell      fredgc@member.ams.org