Often I'm in a situation where I need a simple RAII wrapper, but I wouldn't want to create a whole new class for this for many reasons including time constraints and organization problems. My quick-n-dirty solution is the following.
Say I want to make sure that by the end of the scope, I want a boolean to switch back to its original state:
bool prevState = currState;
currState = newState;
std::unique_ptr<int, std::function<void(int*)>> txEnder(new int(0), [&prevState](int* p) {
currState = prevState;
delete p;
});
This solution works fine, but the dirty part is the necessity to allocate and deallocate that integer just to make unique_ptr
work and call the custom destructor at destruction.
Is there a cleaner way to do this without having to write a whole class, and get rid of the new
for the dummy int
?
BOOST_SCOPE_EXIT
, right? – Contrapositionif(!ptr) delete ptr;
. I don't see how else. – Drippsdelete
onnullptr
is a noop. IRC, it's UB to do anything else if you overload it. – Flintshire