Why is it allowed to pass R-Values by const reference but not by normal reference?

后端 未结 5 1160
予麋鹿
予麋鹿 2020-11-28 09:10

as the title says why is it allowed to pass R-Values(literals) by constant reference but not normal reference

void display(const int& a)
{
cout <<         


        
5条回答
  •  自闭症患者
    2020-11-28 09:38

    Think of any object as the box containing some value inside and the box may or may not have name tag, i.e. the box with name tag as variable and the box without name tag as literal. Whether name tag is there or not, we have the box.


    Reference is the way that we add name tag to our box.

    int a = 5;
    int &b = a;
    

    we have two name tags for our box (with value 5 inside).

    const int &c = 5;
    

    there you are, the box was just named.


    The new name of the box that has never had a name before must be marked as const. Because the value inside the box can be changed through its name, which we do not want it to happen (not allowed to happen) to our literal box.

提交回复
热议问题