Domanda

Rvalues cannot be used to initialize lvalue (normal) references. But if I write a helper conversion function, it works. What is going on in the background and is it possibly dangerous?

template <class T>
inline T& getLvalueRef(T&& x)
{
    return x;
}

The compiler accepts this.

And then

int ten = 10;
int& ref = getLvalueRef(ten+8);

// use some variables to rewrite memory
int a = 7;
int b = 10;
int c = (a+b)*6;

// check if still works
cout << ref << endl; // okay, still 18
ref = 9;
cout << ref << endl; // okay, 9
È stato utile?

Soluzione

Your code invokes undefined behaviour. ten+8 creates a temporary, whose lifetime ends at the end of the full-expression in which it appears (in your case, the semicolon). getLvalueRef then returns a reference to this temporary.

Any usage of this reference past the full-expression in which ten+8 was created is not allowed.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top