Topic: scope_guard


Author: restor <akrzemi1@gmail.com>
Date: Mon, 21 Dec 2009 12:01:13 CST
Raw View
Hi,
Is a scope guard functionality not general-purpose enough, to be
included in the standard library? This would solve all those
requirements for "finally" keyword that destructors cannot handle. We
would just write:

   std::scope_guard g = [&]{ if(elem.incomplete()) x.rollback(); };

also the implementation appears to be trivial in C++0x:

   class scope_guard : non_copyable
   {
     function<void()> fun;

   public:
     scope_guard( function<void()> fun ) fun(fun) {}
     ~scope_guard(){ fun(); }
   };

Is the C++0x standard library also closed for new features?
Regards,
&rzej

--
[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@netlab.cs.rpi.edu]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://www.comeaucomputing.com/csc/faq.html                      ]





Author: SG <s.gesemann@gmail.com>
Date: Mon, 21 Dec 2009 19:09:24 CST
Raw View
On 21 Dez., 19:01, restor <akrze...@gmail.com> wrote:
> Hi,
> Is a scope guard functionality not general-purpose enough, to be
> included in the standard library? This would solve all those
> requirements for "finally" keyword that destructors cannot handle. We
> would just write:
>
>    std::scope_guard g = [&]{ if(elem.incomplete()) x.rollback(); };
>
> also the implementation appears to be trivial in C++0x:
>
>    class scope_guard : non_copyable
>    {
>      function<void()> fun;

I think non_copyable it not appropriate if you want to use the copy-
initialization syntax.. The scope guard type should move-only. You can
even get it to work without "runtime polymorphism" (or whatever
std::function does). I already saw a blog article about a C++0xified
scope guard implementation somewhere. Let me check ...

Ok, here it is:
http://pizer.wordpress.com/2008/11/22/scope-guards-revisited-c0x-style/

It's almost a 1:1 copy of Alexandrescu's and Marginean's scope guard
implementation. But it replaces the "mutable bool flag hack" with
rvalue references and move semantics. I think it's preferable over
your implementation involving std::function<>.

> Is the C++0x standard library also closed for new features?

Definitely yes.

Cheers,
SG


--
[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@netlab.cs.rpi.edu]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://www.comeaucomputing.com/csc/faq.html                      ]