You are viewing a plain text version of this content. The canonical link for it is here.
Posted to c-dev@xerces.apache.org by rs...@CaveoSystems.com on 2000/09/25 17:01:14 UTC

Memory and object cleanup class

I've noticed discussion about memory and object reclamation issues,
including resource leaks, delete vs delete[], etc.

We have a class (and some implementation templates) that we use for
all these kinds of thigns.  It's called a resource pool, and is not
unlike the core Apache pool facility.  (But, since it's C++ it's both
better and more complicated. :)

The model is that a CRespool object can allocate memory, and also be
given objects.  When the pool goes away, all memory is released, and
all registered objects are deleted.  We overload the shift operators.

For example:
	extern char* foo(); // returns malloc'd memory
	class Csample;
	CRespool rp;
	char* p = rp.strdup("hello world");
	void* vp = rp.malloc(42);
	void* vp = malloc(42) >> 42;
	p = foo() >> rp;

	CSample* cp = new CSample(...);
	if (six_of_one())
	    rp.addObject(cp);
	else
	    rp <<= cp;
	CSample* cp2 = new CSample(...) >>= rp;

	// Oops, don't want to reclaim cp2
	cp2 << rp;

All of the above allocations get properly cleaned up when rp goes out
of scope.  We find ourselves putting an "rp" member in most of our objects,
and the destructors become pretty minimal.  The malloc method grabs big 
chunks of memory (chunksize is a ctor param), and hands them off without
bookkeeping, since it's all going to go away when the pool is destroyed.

If there's interest, I'll fix up the manpage (what format?) and add
delete[] support.
	/r$