RAII对象,用于还原先前的值 [英] RAII object for restoring previous value

查看:100
本文介绍了RAII对象,用于还原先前的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

也许我已经考虑过了,但是请考虑以下示例:

Perhaps I'm over thinking this but consider the following example:

bool some_state = false;

// ... later ...

some_state = true;
do_something();
some_state = false;

现在想象一下do_something()会抛出.我们不会将some_state设置回false.最好是具有某种自动堆栈,该堆栈会根据范围推入/弹出来记住先前的值:

Now imagine that do_something() can throw. We won't set some_state back to false. What would be nice is to have some sort of automatic stack that pushes/pops based on scope for remembering previous values:

{
    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:(

Does boost have something like this? I can write my own object of course but I want to make sure I'm not reinventing the wheel first. I'm using C++03 on MSVC, so I can't use any fancy new C++11 unfortunately :(

推荐答案

提升确实具有这样的功能.它称为state_saver.它被埋在序列化库中,但是它是有文档的,而且显然是官方的(即,没有详细的名称空间).

Boost does have something like this. It's called state_saver. It's kind of buried in the serialization library, but it is documented and apparently official (i.e. not in some detail namespace).

http://www.boost.org/doc/libs/1_56_0/libs/serialization/doc/state_saver.html

演示: http://rextester.com/NVXUG70771

这篇关于RAII对象,用于还原先前的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆