What happens when passing a reference to a literal in C ++?

What's going on here:

double foo( const double& x ) { // do stuff with x } foo( 5.0 ); 
  • Does the compiler create an anonymous variable and set its value to 5.0?
  • Does x indicate a memory location in read-only memory? This is a strange phrase, I know ...

edit : I forgot the const keyword ...

+6
c ++
source share
2 answers

For this purpose, a temporary variable is created and is usually created on the stack.

You can try const_cast, but this is useless, since you can no longer access the variable after the function returns.

+6
source share
  • Which compiler is likely to create a const literal, but it is not a variable.
  • A non-constant reference cannot point to a literal.

    $ g ++ test.cpp test.cpp: In the 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 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 can pass a literal to refer to a constant 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; } 
+1
source share

All Articles