When advancing the state of an object, use of std::swap
works well for simple objects and pointer swaps. For other in place actions, Boost.ScopeExit
works rather well, but it's not terribly elegant if you want to share exit handlers across functions. Is there a C++11 native way to accomplish something similar to Boost.ScopeExit
but allow for better code reuse?
Using std::unique_ptr and lambdas to advance a state of an object
387 views Asked by Sean At
1
(Ab)use
std::unique_ptr
's custom Deleters as aScopeExitVisitor
or Post Condition. Scroll down to ~7th line ofmain()
to see how this is actually used at the call site. The following example allows for eitherstd::function
or lambdas forDeleter
/ScopeExitVisitor
's that don't require any parameters, and a nested class if you do need to pass a parameter to theDeleter
/ScopeExitVisitor
.Which produces:
On the plus side, this trick is nice because:
std::unique_ptr
instances need to have an object assigned to them (e.g. it's perfectly acceptable to leave unneeded Deleters set tonullptr
)reset()
orrelease()
std::unique_ptr
(s) go out of scopeLastly, using
Boost.ScopeExit
you can forward calls to a helper function or use a conditional similar to what theBoost.ScopeExit
docs suggest withbool commit = ...;
. Something similar to:and there's nothing wrong with that, but like was asked in the original question, how do you share code without proxying the call someplace else? Use
std::unique_ptr
's Deleters asScopeExitVisitors
.