问题:
当你声明一个pointer时,系统会给这个变量分配多少内存?
根据OS的位数,32位返回4个字节,64位8个字节
当你声明一个reference变量时,系统会给这个变量分配多少内存?
不分配空间。reference变量和所关联的变量是同一个变量。
int x;
int &ref=x;
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’).
Compiler 会在编译的时候用x来代替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))