关闭

reference 变量的几个问题

492人阅读 评论(0) 收藏 举报

问题:

当你声明一个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))

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:610501次
    • 积分:9087
    • 等级:
    • 排名:第2124名
    • 原创:259篇
    • 转载:289篇
    • 译文:1篇
    • 评论:102条
    最新评论
    数据结构