I was experimenting with the different value categories introduced with C++11, before I tried a line of code which in my mind doesn't make sense, but compiled anyway with no warnings:
#include <iostream>
using namespace std;
class A
{
public:
int val;
A() : val(10) {}
A(const A& other) : val(other.val) {}
A(A&& other) : val(other.val) {}
};
int main()
{
A& a = A();
cout << a.val << endl; // prints '10'
return 0;
}
The line which concerns me:
A& a = A();
Now, from what I understand (which is probably wrong), A()
is a prvalue. In my mind, this means it is a temporary which has no lifetime beyond the expression it appears in.
Does this not mean that the reference type a
should not be able to bind to it?
I've looked around hard and can't find anywhere where this behaviour is stated to be correct, which is understandable as it doesn't make conceptual sense (to me, at least). The reference type a
is certainly referencing something, since I can access val
as normal.
So my question is, is this code non-standard and only valid according to VS, or is there something here that I've completely misunderstood (which is likely)?