cout<<endl<<&x; //address of ‘x’
cout<<endl<<&ref; //address of ‘ref’
Both addresses will be the same (which is whyworking on ‘x’ is the same as working on ‘ref’).
当一个函数用Pass by reference 的时候，compiler是如何实现的？
As forpass-by-reference, if a language has pointers, pass by reference can be done bypassing pointers by value. The compiler can just have a preprocessing stepwhere it "eliminates" pass by reference by making the followingtranslation:
- For every function parameter that is pass by reference, it changes it to a pointer to that type passed by value (e.g. void func(int &foo) -> void func(int *foo))
- For every use of that pass-by-reference parameter inside that function, change it to an explicit pointer dereference (e.g. foo -> *foo) (with the exception that if it is passed by reference again, don't dereference it)
- Every time that function is called, whatever is passed to the pass-by-reference variable, take the address of it explicitly (e.g. func(bar) -> func(&bar))