OpenTTD

- Main Page
- Related Pages
- Modules
- Namespaces
- Data Structures
- Files

- File List
- Globals

backup_type.hpp
Go to the documentation of this file.
1 /* $Id: backup_type.hpp 19931 2010-06-05 12:16:12Z frosch $ */
2
3 /*
4 * This file is part of OpenTTD.
5 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
6 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
7 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
8 */
9
12 #ifndef BACKUP_TYPE_HPP
13 #define BACKUP_TYPE_HPP
14
15 #include "../debug.h"
16
22 template <typename T>
23 struct Backup {
30 Backup(T &original, const char * const file, const int line) : original(original), valid(true), original_value(original), file(file), line(line) {}
31
39 template <typename U>
40 Backup(T &original, const U &new_value, const char * const file, const int line) : original(original), valid(true), original_value(original), file(file), line(line)
41 {
42 /* Note: We use a separate typename U, so type conversions are handled by assignment operator. */
43 original = new_value;
44 }
45
49 ~Backup()
50 {
51 /* Check whether restoration was done */
52 if (this->valid)
53 {
54 /* We cannot assert here, as missing restoration is 'normal' when exceptions are thrown.
55 * Exceptions are especially used to abort world generation. */
56 DEBUG(misc, 0, "%s:%d: Backupped value was not restored!", this->file, this->line);
57 this->Restore();
58 }
59 }
60
65 bool IsValid() const
66 {
67 return this->valid;
68 }
69
74 const T &GetOriginalValue() const
75 {
76 assert(this->valid);
77 return original_value;
78 }
79
85 template <typename U>
86 void Change(const U &new_value)
87 {
88 /* Note: We use a separate typename U, so type conversions are handled by assignment operator. */
89 assert(this->valid);
90 original = new_value;
91 }
92
96 void Revert()
97 {
98 assert(this->valid);
99 this->original = this->original_value;
100 }
101
105 void Trash()
106 {
107 assert(this->valid);
108 this->valid = false;
109 }
110
114 void Restore()
115 {
116 this->Revert();
117 this->Trash();
118 }
119
124 void Update()
125 {
126 assert(this->valid);
127 this->original_value = this->original;
128 }
129
134 bool Verify() const
135 {
136 assert(this->valid);
137 return this->original_value == this->original;
138 }
139
140 private:
141 T &original;
142 bool valid;
143 T original_value;
144
145 const char * const file;
146 const int line;
147 };
148
149 #endif /* BACKUP_TYPE_HPP */