开发者

Is there a generic "clean-up" class in boost?

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 开发者_如何学Pythoncould 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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜