也许我想太多了,但请考虑以下示例:
bool some_state = false;
// ... later ...
some_state = true;
do_something();
some_state = false;
现在想象一下,do_something()
可以扔。我们不会some_state
回到false
. 最好有某种自动堆栈,根据范围推送/弹出以记住以前的值:
{
scoped_restore res( some_state, true ); // This sets some_state to true and remembers previous value (false)
do_something();
} // At this point, res is destroyed and sets some_state back to false (previous value)
boost有这样的东西吗?我当然可以编写自己的对象,但我想确保我不会先重新发明轮子。我在 MSVC 上使用 C++03,所以很遗憾我不能使用任何花哨的新 C++11 :(