In the expression left() = right(), why is right() sequenced first?

会有一股神秘感。 提交于 2019-12-06 19:12:03

问题


In C++, the expression left() = right() evaluates

  1. right()
  2. left()

in that sequence. The right() goes first, as has been discussed here.

I cannot think of a reason for right() to go first. Can you? I presume that there exists a reason. Otherwise, the standard would hardly say what it says, but consider: right() will return some result. At the machine-code level, does the CPU not need to know where to put the result right() will return before asking right() to return it?

If you happen to know what the standard committee was thinking (because you were in the room or have read the memo), that's great: I'd like to read your answer. However, my actual question is more modest. All I want to know is whether there exists a plausible reason and what that reason might be.


回答1:


In addition to the unintuitive result when doing what Brian showed:

#include <map>
int main() {
    std::map<int, int> m;
    m[0] = m.size(); // before C++17 m[0] could be 0 or 1 - it was implementation defined
}

If we take a the same map but do:

#include <map>
int main() {
    std::map<int, int> m;
    m[0] = Right(); // Right() may throw
}

If Right() throws:

Before C++17 you could get a default constructed element in m[0] (left to right) or m[0] wouldn't be created at all (right to left). In C++17 m[0] will not get created at all.




回答2:


In the proposal P0145 that introduced this evaluation order, the authors gave the following example:

#include <map>
int main() {
    std::map<int, int> m;
    m[0] = m.size();
}

In this situation, left-to-right evaluation would give 1, whereas right-to-left evaluation would give 0. Having the result be 0, thanks to right-to-left evaluation, corresponds more closely to our intuition that the value that should be assigned is the one that existed immediately before the assignment expression was evaluated.



来源:https://stackoverflow.com/questions/55387065/in-the-expression-left-right-why-is-right-sequenced-first

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