lundi 1 juillet 2019

What are the rules about using an rvalue reference on the left side of an equals sign?

So I've been learning about rvalues and rvalue references and have run into some code while experimenting that I can't wrap my head around the errors of.

int&& test1(int& t)
{
    return static_cast<int&&>(t);
}

std::string&& test2(std::string& t)
{
    return static_cast<std::string&&>(t);
}


int main()
{
    int n ;
    std::string s;
    static_cast<int&&>(n) = 9;        //Error: expression must be a modifiable lvalue
    static_cast<std::string&&>(s) = "test";  //Compiles and runs fine
    test1(n) = 4;                     //Error: expression must be a modifiable lvalue
    test2(s) = "hello";               //Compiles and runs fine 
}

I was just wondering what the differences are in how rvalue references of std::strings and ints are handled and why one works and one doesn't.

I'm using Visual Studio 2019 with C++17

Aucun commentaire:

Enregistrer un commentaire