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

眉间皱痕 提交于 2019-12-05 01:42:25

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.

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.

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