0

Why VC compiles this, but GCC does not?

#include <iostream>

struct B
{
    int & x;
};

void func(B & b)
{
    b.x = 5;
}

int main()
{
    int y;

    func(B{y});

    std::cout << y;
}

is not it a redundant restriction that y cannot be changed in this way?

Alexey Starinsky
  • 3,699
  • 3
  • 21
  • 57
  • See (for example) https://stackoverflow.com/questions/8293426/error-invalid-initialization-of-non-const-reference-of-type-int-from-an-rval. Bottom line appears to be that temporaries disappear after the expression is evaluated so cannot be used in a reference-y way. Microsoft probably allow this for the same reason they allow a lot of *other* crufty stuff :-) – paxdiablo Aug 24 '18 at 00:56
  • @paxdiablo Why this "void func(const B & b)" is allowed in this case? – Alexey Starinsky Aug 24 '18 at 01:04
  • you can also bind to rvalue reference (`B&&`) if you want – apple apple Aug 24 '18 at 01:07
  • @Alexey, it's allowed because `B xyzzy; func(xyzzy);` is perfectly acceptable (no disappearing temporaries in that case, just the relatively long-lived `xyzzy` variable). – paxdiablo Aug 24 '18 at 01:10
  • @paxdiablo still is not clear, see https://stackoverflow.com/questions/51996219/what-is-the-difference-between-passing-rvalue-by-const-and-non-const-reference – Alexey Starinsky Aug 24 '18 at 01:16
  • 1
    @Alexey, you need to clarify what is not clear. My first comment linked to an answer that stated (quite rightly) that references must refer to something (unlike pointers). And if you try to refer to something that doesn't exist, that's not valid. My second comment was to answer why you were allowed to have that function prototype at all and the answer to that was that it's allowed for *non-* temporaries. I'm not sure how I can explain it better so would appreciate guidance (a little more detail) on *what* you're actually asking. – paxdiablo Aug 24 '18 at 03:40

0 Answers0