Difference between const reference and normal parameter

前端 未结 7 1995
我寻月下人不归
我寻月下人不归 2020-11-28 01:09
void DoWork(int n);
void DoWork(const int &n);

What\'s the difference?

7条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-28 01:48

    Firstly, there is no concept of cv-qualified references. So the terminology 'const reference' is not correct and is usually used to describle 'reference to const'. It is better to start talking about what is meant.

    $8.3.2/1- "Cv-qualified references are ill-formed except when the cv-qualifiers are introduced through the use of a typedef (7.1.3) or of a template type argument (14.3), in which case the cv-qualifiers are ignored."

    Here are the differences

    $13.1 - "Only the const and volatile type-specifiers at the outermost level of the parameter type specification are ignored in this fashion; const and volatile type-specifiers buried within a parameter type specification are significant and can be used to distinguish overloaded function declarations.112). In particular, for any type T, “pointer to T,” “pointer to const T,” and “pointer to volatile T” are considered distinct parameter types, as are “reference to T,” “reference to const T,” and “reference to volatile T.”

    void f(int &n){
       cout << 1; 
       n++;
    }
    
    void f(int const &n){
       cout << 2;
       //n++; // Error!, Non modifiable lvalue
    }
    
    int main(){
       int x = 2;
    
       f(x);        // Calls overload 1, after the call x is 3
       f(2);        // Calls overload 2
       f(2.2);      // Calls overload 2, a temporary of double is created $8.5/3
    }
    

提交回复
热议问题