scoped: add optional reset modifier

This commit is contained in:
Danny Robson 2019-04-12 16:40:17 +10:00
parent 7b2ae1029c
commit 70a16c7d47
3 changed files with 42 additions and 1 deletions

View File

@ -625,6 +625,7 @@ if (TESTS)
rational
region
roots/bisection
scoped
signal
singleton
stream

View File

@ -25,10 +25,15 @@ namespace cruft::scoped {
~restore ()
{
m_target = m_value;
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
View 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 ();
}