mod_annot editor

Annotate Section

Implicit and Explicit Cleanup

Now, supposing we want to free our resource explicitly before the end of the request - for example, because we're doing something memory-intensive but have objects we can free. We may want to do everything according to normal scoping rules, and just use pool-based cleanup as a fallback to deal with error paths. Since we registered the cleanup, it will run regardless, leading typically to a double-free and a segfault.

Another pool function apr_pool_cleanup_kill is provided to deal with this situation. When we run the explicit cleanup, we unregister the cleanup from the pool. Or we can be a little more clever about it. Here's the outline of a C++ class that manages itself based on a pool, regardless of whether it is explicitly deleted or not:


	class poolclass {
	private:
	  apr_pool_t* pool ;
	public:
	  poolclass(apr_pool_t* p) : pool(p) {
	    apr_pool_cleanup_register(pool, (void*)this,
		myclassCleanup, apr_pool_cleanup_null) ;
	  }
	  virtual ~poolclass() {
	    apr_pool_cleanup_kill(pool, (void*)this, myclassCleanup) ;
	  }
	} ;

If you use C++ with Apache (or APR), you can derive any class from poolclass. Most APR functions do something equivalent to this, using register and kill whenever resources are allocated or cleaned up.