static_cast int 引用 int?

static_cast int to reference to int?

是否允许:

int x = 1;
int r1 = static_cast<int&>(x);
int r2 = static_cast<int&&>(x)

如果是,那么这些转换是什么意思?

这段代码产生的问题:

int x = 1;
int y = 2;
std::swap(x, y); // uses int temp = std::move(x);

static_cast int to reference to int? Is it allowed

是的。这是允许的。

If it is, then what is the meaning of these casts?

转换为相同类型的左值引用在很大程度上是没有意义的,因为它自己使用的变量已经是一个左值。但是,它会影响 decltype 推导,如 所示。如果您需要向下转换对 base 的引用(这与 int 无关),则转换为对另一种类型的引用很有用。

转换为右值引用很有用,因为它将表达式的类型更改为无值。这允许从变量移动。这实际上就是 std::move 所做的。不过,这与 int 没有区别。

static_cast<int&>(x);

不执行任何操作,因为 x 在表达式中使用时已经属于 int& 类型。

static_cast<int&&>(x);

x、l-value 转换为 r-value。这正是 std::move 所做的,T&& 用于实现移动语义。

std::swap 使用 std::move 因为根本没有缺点并且可能会提高性能。移动 ctors/assignments 应该始终至少与复制 ctors/assignments.

一样有效