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

后端 未结 5 1163
予麋鹿
予麋鹿 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:25

    It gets back to the definition of literal. A literal is a constant; e.g.the value of the number 5 will not change, ever, though a variable may change from being assigned the value of 5 to another value. Passing a literal by reference implies that the function may modify it, which is something you can't do to a literal, by definition, which is why the language requires that you modify it with const. I don't think C++ could modify literals even if it let you try, but it still enforces this convention to remind the programmer that a literal value cannot be modified.

    Hope that answers your question!

提交回复
热议问题