Difference on address of const reference to ternary operator between clang and gcc

前端 未结 1 1547
名媛妹妹
名媛妹妹 2021-01-13 09:41

I have a vague idea of what\'s going on here... and it has to do with this but I\'m wondering why clang++ and g++ handle this differently. Where is the undefined behaviour a

相关标签:
1条回答
  • 2021-01-13 10:45

    My answer from this other question from today covers your cases in detail. I'll avoid repeating myself and just summarize.

    If we factor out the templates you have two cases. Case 1:

    const char whatever = 'c';
    const char a = 'a';
    const char & me = (true ? a : whatever);
    

    The second and third operands of the conditional operator are both "lvalue of type const char", so the result is "lvalue of type const char" designating the selected operand. Finally, const char & binds directly to "lvalue of type const char", so &me == &a.

    For case 2:

    char whatever = 'c';
    const char a = 'a';
    const char & me = (true ? a : whatever);
    

    The second and third operand are "lvalue of type char" and "lvalue of type const char". The result of this is "lvalue of type const char" designating the selected operand. As before, const char &me binds directly to an lvalue of type const char, so &me == &a.

    If a compiler prints different addresses for me and a in either case, it is a compiler bug.

    0 讨论(0)
提交回复
热议问题