开发者

Parameter evaluation and undefined behavior

Given this example (which is a simplication of an example in the documentation for boost::multi_index_container about update rollbacks):

#include <iostream>

struct change
{
        int val_;
        change(int const &val) : val_(val)
        {
        }

        void operator() (int &v) const
        {
                v = val_;
        }
};

void do_it(int &v, change const &c1, change const &c2)
{
        c1(v);
        c2(v);
}

main()
{
        int i = 17;
        int orig = i;
        do_it(i,开发者_JAVA技巧 change(11), change(orig));
        std::cout << "i = " << i << std::endl;
}

Is the explicit copy of i (into orig) needed here? Or could this be more simply written as:

        int i = 17;
        do_it(i, change(11), change(i));

In that case, is the value of i after the call to do_it still guaranteed to be 17? Both change parameters would need to be constructed before the body of the function is executed.

Does the language guarantee that all of the parameters be constructed before the function begins? (If there is no guarantee, then the compiler could delay the construction of c2 until after c1's operator() has run and thus the final value would be 11)


All the parameters to a function call are evaluated before the function is called. The order in which the parameters are evaluated is unspecified.

In your case i would still be 17.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜