繁体   English   中英

编译器如何在 const 引用和 rvalue 引用之间做出决定?

[英]How does the compiler decide between const reference and rvalue reference?

这个 C++ 代码:

void f(int& i) {
    cout << "by reference" << endl;
}

void f(const int& i) {
    cout << "by const reference" << endl;
}

void f(int&& i) {
    cout << "by rvalue reference" << endl;
}


int main() {
    int x;
    const int y = 5;

    cout << "f(x): ";
    f(x);

    cout << "f(y): ";
    f(y);

    cout << "f(x+y): ";
    f(x+y);

    cout << "f(move(x)): ";
    f(move(x));

    cout << "f(move(y)): ";
    f(move(y));

    cout << "f(move(x+y)): ";
    f(move(x+y));
}

印刷:

f(x): by reference
f(y): by const reference
f(x+y): by rvalue reference
f(move(x)): by rvalue reference
f(move(y)): by const reference
f(move(x+y)): by rvalue reference

我了解除第五行之外的所有行:为什么“move(y)”不让编译器使用右值引用选择 f 的重载? 我怎样才能让编译器选择这个变体?

为什么“move(y)”不让编译器使用右值引用选择 f 的重载

因为int &&是一个非常量引用,并且参数是const

我怎样才能让编译器选择这个变体?

通过将 function 参数更改为const int && (或从y中删除const ),

但通常您不想使用const右值引用。 移动的重点是从被移动的 object 窃取资源。 如果对它的引用是const ,则不能这样做。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM