fork download
  1. /** @file deferpp.h
  2.   @brief Deferpp (Defer++) is Go-like DEFER construction for C++11
  3.  
  4.   Single header. No installation required, no build needed.
  5.   Copy this whole file to any location you like :)
  6.   Created by Pavlo M, https://g...content-available-to-author-only...b.com/olvap80
  7.  
  8.   Usage:
  9. @code
  10.   {
  11.   auto resource = AcquireSomeResource(parameters_here)
  12.   DEFER{ FreeeThatResource(resource); };
  13.  
  14.   ... //work with resource
  15.   }
  16.   //Note: code after DEFER is called when leaving scope due to any reason
  17.   // (one can reach scope end, issue return/break/continue or throw
  18.   // some exception, and there is guarantee deferred code is called)
  19. @endcode
  20.  
  21.   This is quick alternative for RAII: to ensure cleanup code is called
  22.   when scope is exited, so that one does not need to write RAII wrapper
  23.   class for every kind of resource.
  24.   See also sample test fragment (demo) at the bottom of this file.
  25. Copyright (c) 2015-2018, Pavlo M, https://g...content-available-to-author-only...b.com/olvap80
  26. All rights reserved.
  27. Redistribution and use in source and binary forms, with or without
  28. modification, are permitted provided that the following conditions are met:
  29. * Redistributions of source code must retain the above copyright notice, this
  30.   list of conditions and the following disclaimer.
  31. * Redistributions in binary form must reproduce the above copyright notice,
  32.   this list of conditions and the following disclaimer in the documentation
  33.   and/or other materials provided with the distribution.
  34. * Neither the name of deferpp nor the names of its
  35.   contributors may be used to endorse or promote products derived from
  36.   this software without specific prior written permission.
  37. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  38. AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  39. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  40. DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  41. FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  42. DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  43. SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  44. CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  45. OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  46. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  47. */
  48. #ifndef DEFERPP_H_ONCE
  49. #define DEFERPP_H_ONCE
  50.  
  51. #include <utility>
  52.  
  53.  
  54. ///Defer following code until enclosing scope is exited
  55. /** Usage: DEFER{ some_code_to_be_deferred };
  56.   Remember that some_code_to_be_deferred shall not allow
  57.   exceptions to be propagated out of curly braces */
  58. #define DEFER\
  59.   auto DEFER_CAT_ID(callOnScopeExit,__LINE__) \
  60.   = (Defer_SupportNamespace::tagClassForLambda) ->* [&]()
  61.  
  62.  
  63. //==============================================================================
  64. //Implementation details follow
  65.  
  66.  
  67. //Helper macro to expand and concatenate macro arguments into combined identifier
  68. #define DEFER_CAT_ID(a,b) DEFER_CAT_ID_EXPANDED_HELPER(a,b)
  69. //helper macro to concatenate expanded macro arguments
  70. #define DEFER_CAT_ID_EXPANDED_HELPER(a,b) a##b
  71.  
  72. namespace Defer_SupportNamespace{
  73. ///Helper type to trigger operator ->*
  74. struct TagClassForLambda{ constexpr TagClassForLambda(){} };
  75. ///Use this "instance" to trigger overloaded operator ->*
  76. constexpr TagClassForLambda tagClassForLambda;
  77.  
  78. ///RAII for implementing DEFER behavior
  79. template<class Lambda>
  80. class CallOnScopeExit{
  81. public:
  82. constexpr CallOnScopeExit(Lambda&& initialLambda)
  83. : lambda(std::move(initialLambda)), isOwner(true)
  84. {}
  85.  
  86. constexpr CallOnScopeExit(CallOnScopeExit&& other)
  87. : lambda(std::move(other.lambda) ), isOwner(true)
  88. {
  89. other.isOwner = false;
  90. }
  91.  
  92.  
  93. CallOnScopeExit(const CallOnScopeExit& other) = delete;
  94. CallOnScopeExit& operator=(const CallOnScopeExit& other) = delete;
  95.  
  96.  
  97. ~CallOnScopeExit(){
  98. if( isOwner ){
  99. lambda();
  100. }
  101. }
  102.  
  103. private:
  104. Lambda lambda; ///< Hold lambda, avoid slow std::function here
  105. bool isOwner; ///< Ensure 100% lambda is called only one time
  106. };
  107.  
  108. ///Helper operator to easy catch lambda for DEFER macro
  109. /** Use template to avoid slow std::function
  110.   (raw lambda is copied/stored here) */
  111. template<class Lambda>
  112. inline CallOnScopeExit<Lambda> operator ->* (const TagClassForLambda&, Lambda&& lambda){
  113. return CallOnScopeExit<Lambda>(std::move(lambda));
  114. }
  115. }
  116.  
  117.  
  118. //==============================================================================
  119. //Demo (sample test fragment)
  120.  
  121. #if 1
  122.  
  123. #include <iostream>
  124.  
  125. int main() {
  126. int i = 0;
  127. std::cout << "Enter application, i = " << i << std::endl;
  128. {
  129. std::cout << "After enter scope, i = " << i << std::endl;
  130.  
  131. DEFER {
  132. ++i;
  133. std::cout << "Lambda called (apply side effect), i = " << i << std::endl;
  134. };
  135.  
  136. std::cout << "Before exit scope, i = " << i << std::endl;
  137. }
  138. std::cout << "Exit application, i = " << i << std::endl;
  139. return 0;
  140. }
  141.  
  142. /* Expected output is:
  143.   Enter application, i = 0
  144.   After enter scope, i = 0
  145.   Before exit scope, i = 0
  146.   Lambda called (apply side effect), i = 1
  147.   Exit application, i = 1
  148.   */
  149. #endif
  150. #endif /*DEFERPP_H_ONCE*/
Success #stdin #stdout 0.01s 5560KB
stdin
Standard input is empty
stdout
Enter application, i = 0
After enter scope, i = 0
Before exit scope, i = 0
Lambda called (apply side effect), i = 1
Exit application, i = 1