const Reference

Can you explain what is done when we call fuction void Foo(const int& x)

//main.cpp

1
2
3
4
5
6
7
8
void main()
{
....
int a = 6;
Foo(a);

...
}


Thanks in advance!!
that's fairly pointless for primative types, but when passing large objects into a method then passing by ref means you aren't passing the actual object, you're just telling the function where the object is. and making it const means your compiler will guarantee it wont be changed.

http://www.learncpp.com/cpp-tutorial/73-passing-arguments-by-reference/
4: int "a" allocated at stack and filled with 6.
5: address of int "a" (pointer to variable "a", allocated at stack) pushed into stack.
Then Foo() called.
When Foo() started, it reads pointer to variable "a" from stack and uses it as pointer to "x".
So when you read "x", you actually read "a".
Moreover, you can't chage x cause it's marked as const.
If You switch on optimization, compiler can make something else (I dunno what).
So, a wont change
Topic archived. No new replies allowed.