
Alexander Nasonov <alnsn-boost@yandex.ru> writes:
In short, BoostCandidate.Finally is a (better, in my opinion) replacement both for try-finally block and for ScopeGuard. It can be used when RAII approach is not quite applicable. Typical example is VectorInserter class in ScopeGuard article by Andrei Alexandrescu and Petru Marginean ( http://tinyurl.com/26vzp ).
Below is a comparison with ScopeGuard approach (typeof registration is omitted for brevity).
// code snipset copied from ScopeGuard article: void User::AddFriend(User& newFriend) { friends_.push_back(&newFriend); ScopeGuard guard = MakeObjGuard( friends_, &UserCont::pop_back); pDB_->AddFriend(GetName(), newFriend.GetName()); guard.Dismiss(); }
// First form of BoostCandidate.Finally void User::AddFriend(User& newFriend) { friends_.push_back(&newFriend); bool dismiss = false; BOOST_FINALLY_BEGIN( (friends_)(dismiss) ) { if(!dismiss) friends_.pop_back(); } BOOST_FINALLY_END; pDB_->AddFriend(GetName(), newFriend.GetName()); dismiss = true; }
How, exactly, is this an improvement on ScopeGuard? It's longer and more complicated, I'll give you that, but those are not usually thought of as virtues. -- Dave Abrahams Boost Consulting www.boost-consulting.com