In the late years of college, I had a course on Compilers. We created a compiler for a subset of C. I have always wondered how a pass-by-ref function call is compiled into assembly in C++.
For what I remember, a pass-by-val function call follows the following procedure:
What's different for pass-by-reference? (int void(int&);)
EDIT:
I may sound totally lost but, if you could help me I'd really appreciate it.
Everyone's answer is basically that it passes the address instead of the value. I understood that to be basically what passing a pointer is. So how come, these two functions, behave differently?:
struct A {
int x;
A(int v){
x = v;
}
};
int byRef(A& v){
v = A(3);
return 0;
}
int byP (A* v){
v = &A(4); //OR new A(4)
return 0;
}
int _tmain(int argc, _TCHAR* argv[])
{
A a (1); A b (2);
byRef(a); byP (&b);
cout << a.x << " " << b.x;
system("pause");
return 0;
}
I know that in byP(A*), v is being passed by value, thus, it won't affect the caller's argument. Then, how would you implement byRef(A&) in terms of A*?
You pass a pointer to the referand, exactly as you would any other pointer, and the callee knows how to use it. Depending on the implementation it therefore might not be on the stack - some parameters are passed in registers in some calling conventions.
There may be other ways to do it, since the C++ standard doesn't specify how references are implemented afaik, and even if they are implemented as pointers I suppose they might be distinguished in the calling convention. Pointers are the most obvious implementation, though.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With