返回的对象是否形式为函数,返回类型是右值引用、右值还是左值?



我是c++新手。对于这个代码

template <typename T>
constexpr bool is_lvalue(T&& x) {
return std::is_lvalue_reference<T>{};
}
int x=9;
int & fun(){
return x;
}

is_lvalue(fun())返回true我理解这一点,因为左值引用毕竟是左值。但是对于代码,

int && fun(){
return move(x);
}

is_lvalue(fun())返回False,即使声明为右值引用的变量也是左值。那么,第二个fun()返回一个右值吗?提前谢谢。

对返回右值引用的函数的函数调用表达式(如fun())本身就是一个xvalue表达式。这与命名右值引用类型的变量不同。作为表达式的变量名总是左值,与变量的类型无关。

xvalue是右值的一种。另一种类型的右值是左值(例如,函数调用返回非引用)。

函数测试表达式是否为左值,而xvalue不是。

在表达式中使用的x本身是一个左值,但是std::move的唯一工作是取一个左值并将其转换为一个xvalue。所以move(x)也是一个x值。

std::move(x)x转换为xvalue,这允许它将被移走。对于拥有资源的对象,这些资源可以有效地移动到到另一个对象。对于基本类型,使用"move"是一个无操作(即,它只是一个拷贝)),因为没有"资源"。更改所有权。

注意:return std::move(x);强制转换会干扰NRVO、RVO和复制省略。在这个特殊的例子中,对于int,但对于更重的对象,它可以是一个悲观化。

/*
lvalue should had been named something like "variable"
prvalue should had been named something like "temporary"
lvalue - left-hand value (call it "variable")
rvalue - right-hand value (call it "temporary", except when it isn't)
prvalue - pure right-hand value (call it "anonymous temporary")
xvalue - expiring value 
glvalue - generalized left-hand value 
glvalue        rvalue
/ (i)         / (m)
/             /           
"variable" lvalue         xvalue        prvalue "temporary"
(iM)          (im)        / (Im) |
bitfield        vexpr       | pmfcall
|     
     
closure
i - identity
m - can be moved from
I - does not have identity (anonymous)
M - cannot be moved from
xvalue - value has identity and can be moved 
lvalue - value has identity and cannot be moved 
prvalue - value does not have identity and can be moved 
bitfield - is a special kind of lvalue
- address CANNOT be taken 
- non-const lvalue reference CANNOT be bound to it 
vexpr - is a special kind of prvalue
- CANNOT be used to initialize references
- CANNOT be used as function argument
pmfcall - is a special kind of prvalue
- CANNOT be used to initialize references
- CANNOT be used as function argument
- CANNOT be used for any purpose at all, except...
- can ONLY be used left-hand argument of functional call operator
*/

最新更新