所以我一直在学习右值和右值引用,并且在实验时遇到了一些代码,我无法理解其中的错误。
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; }
// ^
};
关于c++ - 在等号左侧使用右值引用的规则是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56844137/