Question

I simply want a class that does this:

class cleanup : boost::noncopyable
{
 public:
  typedef boost::function0<void> function;
  explicit cleanup( function f ) : func( f )
  {
  }

  ~cleanup()
  {
    func();
  }
  private:
    function func; 
};

The purpose being that I have this "cleanup" to invoke func when it is deleted. cleanup will be passed around as a shared_ptr.

I have considered also doing it using a custom deleter in boost::shared_ptr. Perhaps I could use boost::shared_ptr and just create with NULL and get func() to take a parameter that it ignores.

The purpose of this all is to abstract out a step I want the class's destructor to perform when the last reference goes out of scope (actually remove itself from the container that holds it without the class having to know about its container).

If I do it with shared_ptr I would possibly pass around one of these:

boost::shared_ptr<void> cleanupObj( NULL, func );

Here the func must take a parameter. I am not 100% sure even that the deleter will always get called if the pointer is NULL so perhaps I need to use a different pointer which makes it start getting "messy" looking.

Is there a standard way to handle this and if not what is the best way?

Was it helpful?

Solution

I believe that there is a Scope Exit library within Boost. However, why not just use the code you wrote in the OP? And, typically, if you have a class within a container, make the container's owner dish out the references and handle what happens when there are none left.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top