什么" const int&"做一个返回类型?

时间:2017-05-29 21:03:23

标签: c++ function reference max const

const int& max(int a[], int length)
{

int i=0;

    for(int j=0; j<length; j++)
        if(a[j]>a[i]) i=j;
    return a[i];
}

int main(){

    int array[] = {12, -54, 0, 123, 63};
    int largest;
    largest = max(array,5);
    cout<< "Largest element is " << largest << endl;
    return 0;
}

所以我的问题是,&#34; const int&amp;&#34;做一个返回类型?为什么我在函数期望引用时返回一个值?

1 个答案:

答案 0 :(得分:1)

通常,返回引用可以避免复制返回值,并且(如果它不是const - 限定的)使您有机会更改“原始”值。返回类型const T&通常与类类型的对象一起使用,例如std::vector,复制可能导致(不必要的)开销。但是,与基本数据类型(如int)一起使用时,传回const int&可能比复制原始int值的开销更大。

此外,在您的示例中,如果您将类型const int&的结果分配给非引用类型,例如int largest = max(...),返回值为“取消引用”并按值分配。因此,您可以更改变量的内容,因为它是const引用值的副本。如果您有类型const int&,并将其分配给类型为const int&的变量,那么您将获得一个引用,但编译器将不允许您更改它的内容。

因此,传递int引用的唯一方法是没有const,这将允许您更改“origninal”值的内容。 请参阅以下代码;希望它有所帮助:

int& max(int a[], int length) {
    return a[3];
}

const int& maxConst(int a[], int length) {
    return a[3];
}

int main(){

    int array[] = {12, -54, 0, 123, 63};

    int largest = max(array,5);
    cout<< "Largest element (value) is " << largest << endl;
    largest = 10;
    cout << "Element at pos 3 is: " << array[3] << endl;

    int largestConst = maxConst(array,5);
    cout<< "Largest element (value) is " << largestConst << endl;
    largestConst = 10;
    cout << "Element at pos 3 is: " << array[3] << endl;

    int &largestRef = max(array,5);
    cout<< "Largest element (ref) is " << largestRef << endl;
    largestRef = 10;
    cout << "Element at pos 3 is: " << array[3] << endl;

    const int &largestRefConst = maxConst(array,5);
    cout<< "Largest element (value) is " << largestRefConst << endl;
    // largestRefConst = 10;  // -> cannot assign to variable with const-qualified type
    //cout << "Element at pos 3 is: " << array[3] << endl;

    return 0;
}

输出:

Largest element (value) is 123
Element at pos 3 is: 123
Largest element (value) is 123
Element at pos 3 is: 123
Largest element (ref) is 123
Element at pos 3 is: 10
Largest element (value) is 10