OXYGENHUB
◆ main openmsx / src / utils / ScopedAssign.hh
679 B · C++ · last changed chore(): initial commit 1 month ago source blame history raw
e8555c89 Andy McCall 1
#ifndef SCOPEDASSIGN_HH
2
#define SCOPEDASSIGN_HH
3
4
#include <utility>
5
6
/** Assign new value to some variable and restore the original value
7
  * when this object goes out of scope.
8
  */
9
template<typename T> class ScopedAssign
10
{
11
public:
12
	ScopedAssign(const ScopedAssign&) = delete;
13
	ScopedAssign(ScopedAssign&&) = delete;
14
	ScopedAssign& operator=(const ScopedAssign&) = delete;
15
	ScopedAssign& operator=(ScopedAssign&&) = delete;
16
17
	template<typename T2 = T>
18
	[[nodiscard]] ScopedAssign(T& var_, T2&& newValue)
19
		: var(var_), oldValue(std::exchange(var, std::forward<T2>(newValue)))
20
	{
21
	}
22
23
	~ScopedAssign()
24
	{
25
		var = std::move(oldValue);
26
	}
27
28
private:
29
	T& var;
30
	T oldValue;
31
};
32
33
#endif