LibQuicR
defer.h
Go to the documentation of this file.
1 // SPDX-FileCopyrightText: Copyright (c) 2024 Cisco Systems
2 // SPDX-License-Identifier: BSD-2-Clause
3 
4 #pragma once
5 
6 #include <utility>
7 
9 #define QUICR_DEFER_CONCAT(a, b) QUICR_DEFER_CONCAT_INNER(a, b)
10 
12 #define QUICR_DEFER_CONCAT_INNER(a, b) a##b
13 
14 #if defined(__clang__) && __clang_major__ >= 21
16 #define QUICR_DEFER_PUSH \
17  _Pragma("clang diagnostic push") _Pragma("clang diagnostic ignored \"-Wthread-safety-analysis\"")
18 
20 #define QUICR_DEFER_POP _Pragma("clang diagnostic pop")
21 #else
23 #define QUICR_DEFER_PUSH
24 
26 #define QUICR_DEFER_POP
27 #endif
28 
35 #define defer(n) \
36  quicr::ScopeGuard QUICR_DEFER_CONCAT(defer_, __LINE__)([&]() { \
37  QUICR_DEFER_PUSH n; \
38  QUICR_DEFER_POP \
39  })
40 
41 namespace quicr {
47  template<typename F>
48  class ScopeGuard
49  {
50  public:
56  explicit ScopeGuard(F&& f)
57  : func(std::forward<F>(f))
58  {
59  }
60 
62  ScopeGuard(const ScopeGuard& other) = delete;
63 
65  ScopeGuard& operator=(const ScopeGuard& other) = delete;
66 
71  ~ScopeGuard() noexcept { func(); }
72 
73  private:
74  F func;
75  };
76 }
Non-copyable RAII guard that invokes a callable at scope exit.
Definition: defer.h:49
~ScopeGuard() noexcept
Invokes the stored callable.
Definition: defer.h:71
ScopeGuard & operator=(const ScopeGuard &other)=delete
Scope guards cannot be copy-assigned.
ScopeGuard(F &&f)
Takes ownership of a callable to run at destruction.
Definition: defer.h:56
ScopeGuard(const ScopeGuard &other)=delete
Scope guards cannot be copied.
Definition: attributes.h:13