右值参数导致的多重实现

Multiple implementation caused by rvalue parameter

这是我的测试代码:

void test(std::vector<int> vec){};
void test(std::vector<int> && vec){};

int main(int argc, char * argv[])
{
    std::vector<int> v;
    test(v);
    test(std::move(v));

    return 0;
}

当我尝试调用 test(std::move(v)) 时,我被告知 test 是乘法实现的。显然我已经使用 std::move 使 v 成为右值。不会专门调用test(std::vector<int> &&)吗?

这与右值或移动没有直接关系。左值引用重载

也会发生同样的情况
void test(std::vector<int> vec){};
void test(std::vector<int> & vec){};

int main(int argc, char * argv[])
{
    std::vector<int> v;
    test(v); // ambiguous

    return 0;
}

两个重载的隐式转换序列是等价的。您的示例仅在移动时突然爆发的原因是第一次调用传递了一个左值(使第二个重载不适用),而再次应用 std::move 会产生两个等效的转换序列。

按值接受参数意味着可以通过移动或复制来初始化参数。因此,如果您在引用上有另一个重载(无论是右值还是左值),该值类别就会出现歧义。