2 * Copyright 2013 Facebook, Inc.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
18 * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com)
20 * @brief This file is the implementation file of scope guard RAII
22 #ifndef DPL_SCOPE_GUARD_H_
23 #define DPL_SCOPE_GUARD_H_
28 #include <type_traits>
29 #include <dpl/preprocessor.h>
32 template<typename FunctionType>
36 explicit ScopeGuard(const FunctionType& function)
37 : m_function{function},
41 explicit ScopeGuard(FunctionType&& function)
42 : m_function{std::move(function)},
46 ScopeGuard(ScopeGuard&& other)
47 : m_function{std::move(other.m_function)},
48 m_released{other.m_released}
53 ScopeGuard(const ScopeGuard&) = delete;
63 ScopeGuard& operator=(const ScopeGuard&) = delete;
70 void* operator new(size_t) = delete;
73 // FIXME change to noexcept when available
74 void Execute() throw()
79 FunctionType m_function;
83 template<typename FunctionType>
84 inline ScopeGuard<typename std::decay<FunctionType>::type>
85 MakeScopeGuard(FunctionType&& function)
87 return ScopeGuard<typename std::decay<FunctionType>::type>(
88 std::forward<FunctionType>(function));
92 enum class ScopeGuardOnExit {};
94 template <typename FunctionType>
95 inline ScopeGuard<typename std::decay<FunctionType>::type>
96 operator+(detail::ScopeGuardOnExit, FunctionType&& function)
98 return ScopeGuard<typename std::decay<FunctionType>::type>(
99 std::forward<FunctionType>(function));
104 // FIXME provide support for compilers not supporting variadic macros;
105 // instead of using variadic macros (for compatibility) we could
106 // capture all by '&' (only referenced variables would be captured)
107 #define DPL_SCOPE_EXIT(...) \
108 auto DPL_ANONYMOUS_VARIABLE(DPL_SCOPE_EXIT_STATE) \
109 = ::DPL::detail::ScopeGuardOnExit() + [__VA_ARGS__]()
111 #endif // DPL_SCOPE_GUARD_H_