const reference can be assigned an int?

后端 未结 2 1560
北恋
北恋 2020-12-08 17:18

I came across a code snippet

const int& reference_to_const_int = 20;
cout<<\"\\n  reference_to_const_int = \"<

        
相关标签:
2条回答
  • 2020-12-08 17:48

    A temporary is created, and it's legal to bind a const reference to it, but illegal to bind it to a non-const one.

    It's just like:

    const int& reference_to_const_int = int(20);  //LEGAL
          int& reference_to_const_int = int(20);  //ILLEGAL
    

    A const reference extends the life of a temporary, that's why this works. It's just a rule of the language.

    0 讨论(0)
  • 2020-12-08 18:15

    This behavior is easier to understand when we look at what happens when we bind a reference to a temporary object. If we write

    const int& reference_to_const_int = 20; //A temporay object int(20) is created.
    

    the compiler transforms above code into something like this:

    int temp = 20;
    const int& reference_to_const_int = temp;
    

    If reference_to_const_int were not const, then we could assign a new value to reference_to_const_int. Doing so would not change literal 20 but would instead change temp, which is a temporary object and hence inaccessible. Allowing only const references to be bound to values requiring temporaries avoids the problem entirely because a const reference is read-only.

    Why do C++ allows const references to accept temporary objects or RVALUES (like literals)?

    The most common places we see references are as function arguments or return values. When a reference is used as a function argument, any modification to the reference inside the function will cause changes to the argument outside the function.

    If function can expect/accept temporary objects or literals as inputs and if the function respects const-ness of the object, making the argument a const reference will allow the function to be used in all situations.

    Temporary objects are always const, so if you don’t use a const reference, that argument won’t be accepted by the compiler.

    void f(int&) {}
    void g(const int&) {}
    int main() 
    {
        //f(1); //Error
        g(1); //OK 
    }
    
    0 讨论(0)
提交回复
热议问题