【发布时间】:2022-07-18 21:15:57
【问题描述】:
在以下代码中:
using namespace std;
int main()
{
int bar=42;
int&& foo=(static_cast<int&&>(bar));
int&& foo2=foo;
return 0;
}
int&& foo=(static_cast<int&&>(bar)); 编译没有问题,但int&& foo2=foo; 给出error: cannot bind rvalue reference of type 'int&&' to lvalue of type 'int'。
这意味着在前一行中,static_cast<int&&>(bar) 必须是一个右值,而在后一行中,foo 是一个左值,尽管两者都具有 int&& 类型。
这对我来说并不令人震惊,因为我完全知道右值引用既可以是左值也可以是右值。
但让我感到困惑的是static_cast<int&&>(bar) 是一个右值,因为我们只是将bar 的数据类型从int 更改为int&&,而不是值类别。
那么这里发生了什么?
static_cast<int&&>(bar) 是纯右值还是极限值?
【问题讨论】:
-
你明白为什么
int foo(int); int &&y = foo(x);有效吗?static_cast也一样。 -
“如何”是通过铸造。
static_cast<int&&>(bar)和std::move(bar)是一回事。强制转换告诉编译器将变量视为右值(特别是 xvalue ......但这是在挑选 nits)。 -
您不应将值类别视为变量的属性(例如类型),而应视为表达式的属性。
标签: c++