当类型为“Class &&”的变量用作参数时,为什么调用复制构造函数而不是移动构造函数

Why copy ctor is called instead of move ctor when variable of type `Class &&` is used as argument

考虑这段代码:

#include <iostream>

struct S
{
    S() {std::cout << "default ctor\n";}
    S(const S&) {std::cout << "copy ctor\n";}
    S(S &&) {std::cout << "move ctor\n";}
};

int main() {
    S base;
    S &&ref = (S&&)base;
    S obj(ref);
    return 0;
}

令人惊讶的是 S obj(ref); 调用复制构造函数而不是移动构造函数。
但是如果我用 S obj((S&&)ref); 替换这一行,那么 move ctor 就会按预期被调用。

为什么会这样?为什么我确实需要强制转换来调用移动构造函数?

作为表达式,ref 是一个 左值 ,任何命名任何类型变量的表达式也是如此。因此它将绑定到 lvalue 引用(对于复制构造函数),但不会绑定到 rvalue 引用(对于移动构造函数)。

使用std::move(或等价的强制转换表达式)给出一个右值表示对象的表达式。这将绑定到 rvalue 引用,因此选择移动构造函数。