How are side effects and observable behavior related in C++?

一笑奈何 提交于 2020-01-13 07:53:06

问题


C++03 Standard 1.9/6 defines observable behavior:

The observable behavior of the abstract machine is its sequence of reads and writes to volatile data and calls to library I/O functions.

and then and then 1.9/7 defines side effects:

Accessing an object designated by a volatile lvalue (3.10), modifying an object, calling a library I/O function, or calling a function that does any of those operations are all side effects, which are changes in the state of the execution environment.

Is a side effect an observable behavior or not? How are they related to each other?


回答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.



来源:https://stackoverflow.com/questions/13271469/how-are-side-effects-and-observable-behavior-related-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!