reference 变量的几个问题

本文详细解释了在C++编程中声明引用和指针时内存分配的差异,以及函数使用引用参数时编译器的实现方式。通过实例演示了引用和指针在内存管理上的不同之处,并阐述了它们在实际编程中的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题:

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值