右值引用到左值引用

右值引用到左值引用

本文介绍了右值引用到左值引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Rvalues不能用于初始化左值(普通)引用。但是,如果我编写了一个辅助转换函数,它将起作用。

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;
}

编译器接受。

然后

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


推荐答案

您的代码会调用未定义的行为。 ten + 8 创建一个临时对象,其生存期在出现该 full-expression 的末尾(在您的情况下为分号) 。 getLvalueRef 然后返回对该临时目录的引用。

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.

该引用在 full-expression之后的任何用法不允许创建 ten + 8 的。

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

这篇关于右值引用到左值引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 14:17