1

所以我一直在学习右值和右值引用,并且在试验时遇到了一些代码,我无法解决这些错误。

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 
}

我只是想知道如何处理 std::strings 和 int 的右值引用有什么区别,以及为什么一个有效而一个无效。

我正在使用带有 C++17 的 Visual Studio 2019

4

1 回答 1

1

因为 C++ 以不同的方式处理类类型和内置类型。

对于内置类型,不能分配右值。

对于类类型,例如std::string,与 ;test2(h) = "hello";相同test2(h).operator=("hello");operator=是 的成员std::string,与其他成员函数没有什么特别之处。如果允许在右值上调用成员,则这是有效operator=的,并且对于std::string::operator=. 你甚至可以写一些类似的东西std::string{} = "hello";,即分配一个临时的,它很快就会被销毁,这确实没有多大意义。

如果要约束用户自定义类的成员函数只能在左值上调用,可以指定左值引用限定符(C++11 起),反之亦然。例如

struct X {
    X& operator=(const char*) & { return *this; }
    //                        ^
};

居住

于 2019-07-02T01:19:26.797 回答