BOOST_SCOPE_EXIT将参数作为值传递

时间:2015-08-07 13:40:49

标签: c++ boost scope

如果这是一个很好的编程习惯,请你告诉我:

  BOOST_SCOPE_EXIT(x, i)

我正在路过价值:

  BOOST_SCOPE_EXIT(&x, &i).

而不是

 Hello i 6 
 Hello i 7 
 Hello i 8 
 Hello i 9 

==

输出结果为:

Hello i 5

所以它确实有用。

值:

BOOST_SCOPE_EXIT(& x,& i)

价值观不同。

--------------------------------------
  page_id  |  page_url |   details   |  
--------------------------------------
      1    |    xxxx   |   wdredrr   |
      2    |    yyyy   |   rdsacsa   |
      3    |    zzzz   |   rscsacc   |
      4    |    aaaa   |   xdsxsxs   |
      5    |    bbbb   |   drxcraa   |
--------------------------------------

也可以打印。

由于

2 个答案:

答案 0 :(得分:0)

由于您需要访问最终值,因此两者都需要作为参考。

您应该能够通过运行具有不同值的程序来验证这一点,并且看到“Hello”永远不会打印出代码原样。

http://www.boost.org/doc/libs/1_56_0/libs/scope_exit/doc/html/scope_exit/tutorial.html

答案 1 :(得分:0)

如果您可以访问c ++ 11或更高版本,我会认为良好的编程习惯会与时俱进。 BOOST_SCOPE_EXIT现在是多余的:

#include <iostream>

// -- snip -- this into a header file
namespace detail {
    template<class Function>
    struct at_scope_exit
    {
        at_scope_exit(Function f) : _f(std::move(f)) {}
        ~at_scope_exit() {
            try {
                _f();
            }
            catch(...) {

            }
        }
        Function _f;
    };
}

template<class Function>
auto at_scope_exit(Function f) -> detail::at_scope_exit<Function>
{
    return { std::move(f) };
}
// -- end snip --

auto main() -> int
{
    std::cout << "By Reference:\n";
    // using by reference:
    {
        int i = 0;
        bool x = false;
        for (int i = 0; i < 10; i++)
        {
            // reference to x is taken here
            auto endscope = at_scope_exit([&x, i] {
                if (x) {
                    std::cout << " Hello" << " i " << i << " " << std::endl;
                }
            });

            if(i == 5)
            {
                x = true;
            }
        }
    }

    std::cout << "\nBy Value:\n";
    // using by value
    {
        int i = 0;
        bool x = false;
        for (int i = 0; i < 10; i++)
        {
            // COPY OF x is taken here
            auto endscope = at_scope_exit([x, i] {
                if (x) {
                    std::cout << " Hello" << " i " << i << " " << std::endl;
                }
            });

            if(i == 5)
            {
                // x set HERE (after the above copy) so it's now different to the lambda's version of x
                x = true;
            }
        }
    }
    return 0;
}

输出:

By Reference:
 Hello i 5 
 Hello i 6 
 Hello i 7 
 Hello i 8 
 Hello i 9 

By Value:
 Hello i 6 
 Hello i 7 
 Hello i 8 
 Hello i 9