c++ - 在等号左侧使用右值引用的规则是什么?

标签 c++ c++11 rvalue-reference lvalue-to-rvalue

所以我一直在学习右值和右值引用,并且在实验时遇到了一些代码,我无法理解其中的错误。

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 和 ints 的右值引用的处理方式有什么区别,以及为什么一种有效而另一种无效。

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

最佳答案

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

对于内置类型,无法分配右值。

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

如果要限制用户定义类的成员函数只能在左值上调用,可以指定 lvalue ref-qualifier (since C++11) , 或相反亦然。例如

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

LIVE

关于c++ - 在等号左侧使用右值引用的规则是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56844137/

相关文章:

c++ - 如果包含 <iostream>,则 operator== 不会编译

c++ - 字符串转 float ,C++实现

c++ - 通过字符串模板参数访问元组

c++ - 显式实例化类模板中的自动构造函数

c++ - 类、右值和右值引用

C++11 vector 在右值上进行复制

c++ - 在不同的 QGraphicsView 之间拖放

c++ - 如何在运行时 C++ 中包含头文件和函数?

c++11 - 作为可变参数模板参数的成员指针

c++ - 为什么右值不能绑定(bind)到非 const 左值引用,除了写入临时值无效这一事实之外?