为什么我们可以从非标量分配右值引用,但从标量分配右值引用时它不起作用,当从函数返回时,但它在局部变量 (wtf) 中工作?
#include <iostream>
#include <cstdlib>
#include <vector>
#include <cstdlib>
#include <cstring>
#include <type_traits>
using std::cout;
using std::endl;
struct A
{
};
int&& f()
{
return 10;
}
A&& g()
{
return {};
}
int main(int argc, char* argv[]) {
// f() = 10; <-- This line doesn't compile
g() = A(); // Works
int&&x = 10;
x = 20; // Works
cout << "ok" << endl;
return EXIT_SUCCESS;
}
你的代码中有两件事。首先是能够分配给类类型的临时(r 值)之间的区别。
struct S{};
S{} = S{}; // ok, S is class type
int{} = int{}; // error, int is an in-built type
这就解释了为什么f() = 10;
不起作用,但g() = A();
起作用。f
返回 r 值为int
,而g
返回类类型 (A
) 的 r 值。
第二个区别是f()
和x
的值类别之间的区别。虽然这两个表达式具有相同的类型,即对int
的 r 值引用 (int&&
),但f()
的值类别是 r 值,而x
的值类别是 l 值(基本上,x
有一个名称,而f()
返回的对象没有)。
f() = 10; // error
x = 20; // ok