所以我一直在学习rvalues和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 and ints的rvalue参考以及一个人不起作用,而一个人不做任何区别。
我正在使用C 17
,因为C 以不同的方式处理类型和建筑类型。
对于建筑类型,RVALUE不能被掩盖。
对于课堂类型,例如std::string
,test2(h) = "hello";
与test2(h).operator=("hello");
相同;operator=
是std::string
的成员,它与其他成员功能并不特别。这是有效的,如果允许在RVALUE上调用成员operator=
,那么std::string::operator=
是正确的。您甚至可以写出诸如std::string{} = "hello";
之类的东西,即将很快销毁的临时性分配,这确实没有太多意义。
如果要约束用户定义类的成员功能,只能在lvalues上调用,则可以指定lvalue ref-Qualifier(自C 11以来(,反之亦然。例如
struct X {
X& operator=(const char*) & { return *this; }
// ^
};
live