4

Possible Duplicate:
How come a non-const reference cannot bind to a temporary object?

There is such code:

void fun_ref(int& par){}

void fun_const_ref(const int& par){}

int main(){

  //fun_ref(2); error: invalid initialization of non-const reference of type ‘int&’ from a temporary of type ‘int’
  fun_const_ref(2);

  char var = 3;
  //fun_ref(var); error: invalid initialization of reference of type ‘int&’ from expression of type ‘char’
  fun_const_ref(var);
  return 0;
}

Why is it possible to pass rvalue and different data type than type of function parameter for constant reference, but it is not possible for non-constant reference?

Community
  • 1
  • 1
scdmb
  • 15,091
  • 21
  • 85
  • 128

3 Answers3

3

When the argument is a const reference and the argument passed is not of that type but there is an implicit conversion to that type, the implementation will hold the value in a temporary and use such temporary as argument. So the const version is not taking a reference to char var but to int __temp.

K-ballo
  • 80,396
  • 20
  • 159
  • 169
1

In the first case, 2 is a temporary so it can only be bound to a const reference; that's why you cannot call fun_ref with it.

In the second case, var is a char so it cannot be bound to an int&. However, it is possible for var to be converted to a temporary int, which can be bound to a const int& as above; that one works due to the implicit coversion.

Jon
  • 428,835
  • 81
  • 738
  • 806
0

The compiler can create a temporary of the function argument type by implicit conversion and pass it as a const reference. This does not work for a reference type, since temporaries cannot be passed as non-const references.

Edit: Non-const references to temporaries are disallowed because the standard says so. The reason behind this is that a function getting a non-const reference will change its argument (or else you could have made the reference const), and these changes will be lost when the temporary goes out of scope.

thiton
  • 35,651
  • 4
  • 70
  • 100