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
81 FunctionType m_function;
85 template<typename FunctionType>
86 inline ScopeGuard<typename std::decay<FunctionType>::type>
87 MakeScopeGuard(FunctionType&& function)
89 return ScopeGuard<typename std::decay<FunctionType>::type>(
90 std::forward<FunctionType>(function));
94 enum class ScopeGuardOnExit {};
96 template <typename FunctionType>
97 inline ScopeGuard<typename std::decay<FunctionType>::type>
98 operator+(detail::ScopeGuardOnExit, FunctionType&& function)
100 return ScopeGuard<typename std::decay<FunctionType>::type>(
101 std::forward<FunctionType>(function));
106 // FIXME provide support for compilers not supporting variadic macros;
107 // instead of using variadic macros (for compatibility) we could
108 // capture all by '&' (only referenced variables would be captured)
109 #define DPL_SCOPE_EXIT(...) \
110 auto DPL_ANONYMOUS_VARIABLE(DPL_SCOPE_EXIT_STATE) \
111 = ::DPL::detail::ScopeGuardOnExit() + [__VA_ARGS__]()
113 #endif // DPL_SCOPE_GUARD_H_