This is an automated email from the ASF dual-hosted git repository.
wangdan pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/incubator-pegasus.git
The following commit(s) were added to refs/heads/master by this push:
new 079de23e2 feat(util): add cancel() for class defer (#1458)
079de23e2 is described below
commit 079de23e24d83a758a363780f0f09f8d081f2dc7
Author: Yingchun Lai <[email protected]>
AuthorDate: Thu Apr 20 11:02:10 2023 +0800
feat(util): add cancel() for class defer (#1458)
https://github.com/apache/incubator-pegasus/issues/887
Add function cancel() for class defer to cancel the callback, it's useful
if using defer to short circuit failures and cancel it after all conditions
passed.
For example:
```c++
auto cleanup = dsn::defer([this]() { release_db(); });
RETURN_NOT_OK(a);
RETURN_NOT_OK(b);
RETURN_NOT_OK(c);
cleanup.cancel();
```
---
src/utils/defer.h | 10 +++++++++-
1 file changed, 9 insertions(+), 1 deletion(-)
diff --git a/src/utils/defer.h b/src/utils/defer.h
index 740085d63..1781c82e6 100644
--- a/src/utils/defer.h
+++ b/src/utils/defer.h
@@ -50,8 +50,16 @@ template <typename Func>
struct deferred_action
{
explicit deferred_action(Func &&func) noexcept : _func(std::move(func)) {}
- ~deferred_action() { _func(); }
+ void cancel() { _cancelled = true; }
+ ~deferred_action()
+ {
+ if (!_cancelled) {
+ _func();
+ }
+ }
+
private:
+ bool _cancelled = false;
Func _func;
};
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]