c++ - C++ 中的副作用和可观察行为如何相关?

标签 c++ side-effects

C++03 标准 1.9/6 定义了可观察行为:

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 定义了副作用:

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.

副作用是可观察到的行为吗?它们之间的关系如何?

最佳答案

不,副作用不一定是可观察到的行为。例如,修改非 volatile 对象是一种副作用,但不可观察。区别很重要,因为编译器可能会重新排列或完全删除副作用,只要可观察的行为保持不变。

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

如果需要,大多数编译器会完全删除 a。这是允许的。分配和添加是不可观察的。

所有可观察到的行为都必然是副作用。

关于c++ - C++ 中的副作用和可观察行为如何相关?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13271469/

相关文章:

c++ - 当同一个信号可以来自多个地方时使用 Qt 的信号和槽

perl - Data::Dumper() 的副作用是什么?

c++ - 读取 2 个整数并在 while 循环中打印它们的程序给出 range_error

C++ 从 parent 的 vector 中调用 child 的方法?

c# - 修改引用类型参数的方法不好吗?

inheritance - 错误或功能 : Kotlin allows to change 'val' to 'var' in inheritance

python - 在这种情况下允许 Python monkey patching 的机制是什么?

delphi - writeln (“:width” 说明符的明显副作用会导致输出中出现问号)

c++ - C++ 模板基类的编译器警告

c++ - 绑定(bind)后编译器抛出错误 "expected initializer before int"一直在尝试学习 c++,我只是一直卡住