简体   繁体   中英

Why I can't assign function returning rvalue reference when it's a int but I can when it's a class?

Why we can assign rvalue reference from a non-scalar but from a scalar it does not work, when returning from function, but works in local variable (wtf)?

#include <iostream>
#include <cstdlib>
#include <vector>
#include <cstdlib>
#include <cstring>
#include <type_traits>

using std::cout;
using std::endl;

struct A
{
};

int&& f()
{
    return 10;
}

A&& g()
{
    return {};
}

int main(int argc, char* argv[]) {
    
    // f() = 10; <-- This line doesn't compile
    g() = A(); // Works

    int&&x = 10;
    x = 20; // Works

  cout << "ok" << endl;
    return EXIT_SUCCESS;
}

There's two things going on in your code. The first is the difference between being able to assign to temporaries (r-values) of class type.

struct S{};
S{} = S{};     // ok, S is class type
int{} = int{}; // error, int is an in-built type

This explains why f() = 10; doesn't work, but g() = A(); does. f returns a r-value of int , while g returns a r-value of class type ( A ).


The second difference is between the value categories of f() and x . While both these expressions have the same type , ie r-value reference to int ( int&& ), the value category of f() is an r-value, while that of x is an l-value (basically, x has a name, whereas the object returned by f() doesn't).

f() = 10;  // error
x = 20;    // ok

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM