Are return types considered as rvalues?

时间:2015-06-26 09:47:21

标签: c++

Just a simple question, i am trying to simulate a bad practice when it comes to returning &&. I am aware that it's a bad practice.

Here is an example

//dummy is just an empty class
dummy && crashtest(){
    dummy temp;
    return std::move(temp);

}


int main() {
    dummy && k = crashtest();
    return 0;
}

This is a bad practice because k now holds a reference to the destructed temp inside the function.

I tried a different approach by doing something like this inside my main:

dummy l; //generate temp
dummy && k =  std::move(l); //return value
dummy && d = k; // copy

though l won't really be destroyed, how come it won't let me compile? I get an error saying that i am trying to bind an lvalue. isn't it the same as what happens in function? From my understanding, what happened in function was:

temp is created -> std::move(temp) -> return type dummy&& receives it -> k is equalized to the return type temporary.

I need clarification. Is the return type considered an rvalue ?

Bonus question: what happens if an rvalue reference variable is equalized to an rvalue reference variable? &&lhs = &&rhs, does lhs takes the rhs reference?

1 个答案:

答案 0 :(得分:3)

从函数返回rvalue引用很可能会导致悬空引用(引用存在,但它引用的临时对象已被破坏)。 这实际上在标准中称为xvalue(“eXpiring”值)。