Rvalue reference to lvalue reference

风格不统一 提交于 2019-12-11 11:26:21

问题


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

回答1:


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.



来源:https://stackoverflow.com/questions/23629745/rvalue-reference-to-lvalue-reference

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