繁体   English   中英

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

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

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

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

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

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

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

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

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

居住

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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