Reference vs Pointer

参考自Dan Saks的文章

An Introduction to References

References and const

The key insights

I believe the key insight into why C++ has reference types as well as pointer types is that reference types enable overloaded operators to look like built-in operators, as well as act like them.

Pointers can do almost everything that references can do, but they can lead to expressions that don't look right. On the other hand, references have some restrictions that make them less convenient than pointers for implementing algorithms and data structures. References reduce, but do not eliminate, the need for pointers.

As a general rule, use references in function parameters and return types to define attractive interfaces. Use pointers to implement algorithms and data structures.

Samples:

1) int *x[n]            //[] has higher precedence than*.

    It means that x is an "array withN elements of type pointer"

2) char *f(int)      //() has the same precedence as [].

    It means that f is a function returning a pointer to achar.

3) char (*f)(int)   

    It means that f is a pointer to a function returning achar.

4) char &g(int)

    It means that g is a function returning a reference to achar.

5) char (&g)(int)

    It means that g is a reference to a function returning a char.

6) const int &ri = i  is equivalent toint const &ri = i

    因为reference天生就是const所以只有指向常量的引用而没有常量引用的说法。

    int &const rj = j; // error

7) int const *p = &i               //pointer toconst

8) int *const q = &j               //const pointer

 

假设有对象定义:
MyObjectType obj1;

1. 值传递:
如果函数定义为:
void myFunction( MyObjectType obj);

函数调用:
myFunction(obj); //函数以外对象obj的值不会 改变

2. reference传递:
如果函数定义为:
void myFunction( MyObjectType &obj);

函数调用:
myFunction(obj); //函数以外对象obj的值 改变

3. 指针传递:
如果函数定义为:
void myFunction( MyObjectType *obj);

函数调用:
myFunction(&obj); //需要dereference(&), 函数以外对象obj的值 改变

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值