2
* Copyright © 2013 Canonical Ltd.
4
* This program is free software: you can redistribute it and/or modify
5
* it under the terms of the GNU Lesser General Public License version 3 as
6
* published by the Free Software Foundation.
8
* This program is distributed in the hope that it will be useful,
9
* but WITHOUT ANY WARRANTY; without even the implied warranty of
10
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11
* GNU Lesser General Public License for more details.
13
* You should have received a copy of the GNU Lesser General Public License
14
* along with this program. If not, see <http://www.gnu.org/licenses/>.
16
* Authored by: Alan Griffiths <alan@octopull.co.uk>
23
#include <type_traits>
27
/// Utilities for exception safe use of paired function calls
30
template <typename Creator, typename Deleter>
33
PairedCalls(Creator&& creator, Deleter&& deleter) : deleter(std::move(deleter)), owner(true) { creator(); }
34
PairedCalls(PairedCalls&& that) : deleter(that.deleter), owner(that.owner) { that.owner = false; }
35
~PairedCalls() { if (owner) deleter(); }
37
PairedCalls(PairedCalls const& that) = delete;
38
PairedCalls& operator=(PairedCalls const& that) = delete;
39
Deleter const deleter;
44
* Creates an RAII object from a creator and deleter.
45
* If creator returns a pointer type then the returned object
46
* is a std::unique_ptr initialized with the pointer and deleter.
47
* Otherwise, the returned object calls creator on construction and deleter on destruction
49
* \param creator called to initialize the returned object
50
* \param deleter called to finalize the returned object
52
template <typename Creator, typename Deleter>
53
inline auto paired_calls(Creator&& creator, Deleter&& deleter)
54
-> std::unique_ptr<typename std::remove_reference<decltype(*creator())>::type, Deleter>
56
return {creator(), deleter};
60
template <typename Creator, typename Deleter>
61
inline auto paired_calls(Creator&& creator, Deleter&& deleter)
62
-> typename std::enable_if<
63
std::is_void<decltype(creator())>::value,
64
PairedCalls<Creator, Deleter>>::type
66
return {std::move(creator), std::move(deleter)};
70
* Creates an RAII object from an owning pointer and deleter.
71
* The returned object is a std::unique_ptr initialized with the pointer and deleter.
73
* \param owned the object to take ownership of
74
* \param deleter called to finalize the owned object
76
template <typename Owned, typename Deleter>
77
inline auto deleter_for(Owned* owned, Deleter&& deleter)
78
-> std::unique_ptr<Owned, Deleter>
80
return {owned, deleter};
85
#endif /* MIR_RAII_H_ */