C cout副作用测序

前端之家收集整理的这篇文章主要介绍了C cout副作用测序前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
假设以下代码
#include <iostream>
using namespace std;

char one()
{
    cout << "one\n";
    return '1';
}

char two()
{
    cout << "two\n";
    return '2';
}

int main(int,char**)
{
    // 1:
    cout << one()
         << '\n'
         << two()
         << '\n';

    // 2:
    operator<<(
        operator<<(
            operator<<(
                operator<<(
                    cout,one()),'\n'),two()),'\n');
}

标记为1和2的行的执行与ideone编译一样,它打印如下:

two
one
1
2

从我的观点来看,我们在这里观察到的是未指定的行为,因为函数参数被解析的顺序是未指定的.

这是访问中的一个问题,打印上面给出的顺序(没有任何替代)应该是正确的答案,但它是否正确?

解决方法

你是对的,面试官对语言及其规则表现出一种令人惊讶的普遍缺乏的理解.

这两行是严格等效的,如果每个运算符<<要求第一行总是一个免费的功能(标准说是他们). 正如你所想的那样,函数调用之间的顺序,除了其中一个参数是另一个参数的返回值,是不确定的顺序(前后,但未指定哪个):

1.9 Program execution [intro.execution]

[…]
15 […]
When calling a function (whether or not the function is inline),every value computation and side effect associated with any argument expression,or with the postfix expression designating the called function,is sequenced before execution of every expression or statement in the body of the called function. [ Note: Value computations and side effects associated with different argument expressions are unsequenced. —end note ] Every evaluation in the calling function (including other function calls) that is not otherwise specifically sequenced before or after the execution of the body of the called function is indeterminately sequenced with respect to the execution of the called function.9 Several contexts in C++ cause evaluation of a function call,even though no corresponding function call Syntax appears in the translation unit. [ Example: Evaluation of a new expression invokes one or more allocation and constructor functions; see 5.3.4. For another example,
invocation of a conversion function (12.3.2) can arise in contexts in which no function call Syntax appears. —end example ]
The sequencing constraints on the execution of the called function (as described above) are features of the function calls as evaluated,whatever the Syntax of the expression that calls the function might be.

命名所有部分:

cout << one() // a) execute one()           ("one\n")
              // b) output the return-value ("1")
     << '\n'  // c) output newline          ("\n")
     << two() // d) execute two()           ("two\n")
              // e) output the return-value ("2")
     << '\n'; // f) output newline          ("\n")

订购约束:

a < b < c < e < f
d < e < f

或不同的表示:

a < b < c <
          < e < f
d         <

因此,所有有效的全部订单:

abcdef "one\n1\ntwo\n2\n"
abdcef "one\n1two\n\n2\n"
adbcef "one\ntwo\n1\n2\n"
dabcef "two\none\n1\n2\n"

猜你在找的C&C++相关文章