- What compiler probably does create const literal, but that's not a variable.
A non-const reference cannot point to a literal.
$ g++ test.cpp
test.cpp: In function int main()':
test.cpp:10: error: invalid initialization of non-const reference of type 'double&' from a temporary of type 'double'
test.cpp:5: error: in passing argument 1 of
double foo(double&)'
test.cpp:
#include <iostream>
using namespace std;
double foo(double & x) {
x = 1;
}
int main () {
foo(5.0);
cout << "hello, world" << endl;
return 0;
}
On the other hand, you could pass a literal to a const reference as follows.
test2.cpp:
#include <iostream>
using namespace std;
double foo(const double & x) {
cout << x << endl;
}
int main () {
foo(5.0);
cout << "hello, world" << endl;
return 0;
}