Reputation: 21556
What happens here:
double foo( const double& x ) {
// do stuff with x
}
foo( 5.0 );
edit: I forgot the const keyword...
Upvotes: 7
Views: 2242
Reputation: 95654
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;
}
Upvotes: 1
Reputation: 170509
A temporary variable is created for this purpose and it's usually created on stack.
You could try to const_cast, but it's pontless anyway, since you can no longer access a variable once the function returns.
Upvotes: 6