The Battle for Wesnoth  1.15.12+dev
guard_value.hpp
Go to the documentation of this file.
1 /*
2  Copyright (C) 2003 - 2018 the Battle for Wesnoth Project https://www.wesnoth.org/
3 
4  This program is free software; you can redistribute it and/or modify
5  it under the terms of the GNU General Public License as published by
6  the Free Software Foundation; either version 2 of the License, or
7  (at your option) any later version.
8  This program is distributed in the hope that it will be useful,
9  but WITHOUT ANY WARRANTY.
10 
11  See the COPYING file for more details.
12 */
13 
14 #pragma once
15 
16 namespace utils {
17 
18 /**
19  * Data-based RAII scope guard.
20  * Assigns a value to a specific location, then restores the old value once it goes out of scope.
21  */
22 template<typename T>
23 class guard_value {
24  T* ref_;
26 public:
27  /**
28  * @param ref The memory location being guarded
29  * @param new_val The new value to temporarily assign to that location
30  */
31  guard_value(T& ref, T new_val)
32  : ref_(&ref)
33  , old_val_(ref)
34  {
35  ref = new_val;
36  }
38  {
39  *ref_ = old_val_;
40  }
41 };
42 
43 }
Data-based RAII scope guard.
Definition: guard_value.hpp:23
guard_value(T &ref, T new_val)
Definition: guard_value.hpp:31