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

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

    An r-value is a temporary evanescent object, that can be read but is about to be destroyed. It is also a value that cannot stay on the left-hand side of an assignment (how could you make sense of assigning values to such a ghost?)

    C++ has a very specific way to deal with this kind of entities. If you could pass an r-value by (non-const) reference, you could also be able to assign to it from inside the function. Therefore the rule that if r-values are to be passed by reference, this has to be a const reference.

    This is not the whole truth though, because you have, indeed, r-value references (denoted with &&). So, you can, in the end, manipulate a temporary object, but you have to make an explicit statement that you really want to do so, using r-value references.

提交回复
热议问题