为什么我们可以从非标量分配右值引用,但从标量分配它不起作用,当从函数返回时,但在局部变量 (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
返回 int
的右值,而 g
返回类类型 (A
) 的右值.
第二个区别是 f()
和 x
的值类别。虽然这两个表达式具有相同的类型,即对int
(int&&
) 的右值引用,但f( )
是一个右值,而 x
是一个左值(基本上,x
有一个名称,而 返回的对象f()
没有)。
f() = 10; // error
x = 20; // ok
关于c++ - 为什么当它是一个 int 时我不能分配返回右值引用的函数,但当它是一个类时我可以?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67237903/