如何副作用和C ++相关的可观察的行为?(How are side effects and obse

2019-08-02 10:10发布

C ++ 03标准1.9 / 6限定可观察到的行为

抽象机的观察到的行为是其序列读取和写入非易失性数据和调用库I / O功能。

然后,然后1.9 / 7限定的副作用

访问由挥发性左值(3.10)指定的对象,修改对象,调用库I / O功能,或调用做任何这些操作都是副作用,这是在执行环境中的状态变化的功能。

是副作用的观察行为或不? 他们如何彼此相关?

Answer 1:

No, a side effect is not necessarily observable behaviour. Modifying a non-volatile object, for example, is a side effect, but not observable. The difference matters because the side effects may be rearranged or removed altogether by the compiler, so long as the observable behaviour remains the same.

int main()
{
    int a;
    a = 30;
    a += 2;
    return 0;
}

Most compilers will, if requested, remove a completely. That's permitted. The assignments and addition aren't observable.

All observable behaviour must necessarily be a side effect though.



文章来源: How are side effects and observable behavior related in C++?