scoped: add optional reset modifier
This commit is contained in:
parent
7b2ae1029c
commit
70a16c7d47
@ -625,6 +625,7 @@ if (TESTS)
|
||||
rational
|
||||
region
|
||||
roots/bisection
|
||||
scoped
|
||||
signal
|
||||
singleton
|
||||
stream
|
||||
|
@ -25,10 +25,15 @@ namespace cruft::scoped {
|
||||
|
||||
~restore ()
|
||||
{
|
||||
if (m_restore)
|
||||
m_target = m_value;
|
||||
}
|
||||
|
||||
/// Disable restoration of the value.
|
||||
void reset (void) { m_restore = false; }
|
||||
|
||||
private:
|
||||
bool m_restore = true;
|
||||
ValueT &m_target;
|
||||
ValueT const m_value;
|
||||
};
|
||||
|
35
test/scoped.cpp
Normal file
35
test/scoped.cpp
Normal file
@ -0,0 +1,35 @@
|
||||
#include "scoped.hpp"
|
||||
#include "tap.hpp"
|
||||
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
void test_restore (cruft::TAP::logger &tap)
|
||||
{
|
||||
int value = 42;
|
||||
|
||||
{
|
||||
cruft::scoped::restore raii (value);
|
||||
tap.expect_eq (value, 42, "restorer constructor doesn't modifier value");
|
||||
value = 7;
|
||||
}
|
||||
|
||||
tap.expect_eq (value, 42, "restorer restores value at destruction");
|
||||
|
||||
|
||||
{
|
||||
cruft::scoped::restore raii (value);
|
||||
value = 7;
|
||||
raii.reset ();
|
||||
}
|
||||
|
||||
tap.expect_eq (value, 7, "restorer reset doesn't modify value at destruction");
|
||||
}
|
||||
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
int main ()
|
||||
{
|
||||
cruft::TAP::logger tap;
|
||||
test_restore (tap);
|
||||
return tap.status ();
|
||||
}
|
Loading…
Reference in New Issue
Block a user