Reference variable is not allocated memory

Here is a memory map; a representation of memory as a sequence of blocks:

    address    01   02   03
             +----+----+----+...
data within  | 23 | 6f | 4a |
             +----+----+----+...

Now suppose we create a character:

char c = 'z';  // 'z' is 7a in hex

Further suppose c is stored at address 01, so our memory looks like so:

    address    01   02   03
             +----+----+----+...
data within  | 7a | 6f | 4a |
             +----+----+----+...
Now, let's create a pointer:
char* p = &c;  // point at c

p may be stored at address 02:

    address    01   02   03
             +----+----+----+...
data within  | 7a | 01 | 4a |
             +----+----+----+...
 

Here the pointer p is at address 02 and it points at address01. That's the meaning ofp = &c;. When we dereference the pointerp (at address02) we look at what's in the address pointed at byp. That is,p points at address 01, and so dereferencingp means looking inside address01.

Finally, lets create a reference:

char& r = c;

Here the memory layout doesn't change. That is, no memory is used to store r. r is a sort of alias for c, so when we refer tor we practically refer toc. r and c are conceptually one. Changingr means changingc, and changing c means changingr.

When you create a reference you must initialize, and once initialized you cannot re-initialize it with another target. That is, above the referencer means and forever will meanc.

Also related are const references. These are the same as a reference, except they are immutable:

const char& r = c;
r = 'y';  // error; you may not change c through r
c = 'y'   // ok. and now r == 'y' as well

We use const references when we are interested in reading the data but frown upon changing it. By using a const reference the compiler will not copy the data, so this gives us ideal performance, but also forbid us from changing the data, for correctness.

In a sense, you can say that references are a compile-time feature, whereas pointers are a runtime feature. So references are faster and cheaper than pointers, but come with certain constraints and implications. Like other compile-time-vs-runtime alternatives, we sometimes pick one over the other for performance, sometimes for static analysis and sometimes for flexibility.

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值