编译器如何确定const引用和rvalue引用?

问题描述 投票:0回答:1

此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的重载?以及如何使编译器选择此变体?

c++ move-semantics
1个回答
0
投票

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

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

以及如何使编译器选择此变体?

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

但是通常您不想使用const右值引用。移动的全部目的是从要移动的对象中窃取资源。如果对它的引用是const,则不能执行此操作。

© www.soinside.com 2019 - 2024. All rights reserved.