指针和参考参数之间的差异? [英] difference between a pointer and reference parameter?

查看:97
本文介绍了指针和参考参数之间的差异?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这些是相同的:

int foo(bar* p) {
  return p->someInt();
}

int foo(bar& r) {
  return r.someInt();
}

忽略空指针的潜力。无论 someInt()是虚拟的还是传递 bar 或子类,这两个函数在功能上是否相同 bar

Ignore the null pointer potential. Are these two functions functionally identical no matter if someInt() is virtual or if they are passed a bar or a subclass of bar?

这是否切片:

bar& ref = *ptr_to_bar;


推荐答案

C ++引用有意不在标准中指定为使用指针实现。引用更像是变量的同义词,而不是指向它的指针。

C++ references are intentionally not specified in the standard to be implemented using pointers. A reference is more like a "synonym" to a variable than a pointer to it. This semantics opens some possible optimizations for the compiler when it's possible to realize that a pointer would be an overkill in some situations.

另外还有一些区别:


  • 不能将NULL分配给引用。
    这是一个关键的区别,
    主要原因你更喜欢一个比
    其他。

  • 当您获取
    指针的地址时,您会得到
    指针变量的地址。当您获取引用的
    地址时,您将获得引用的
    变量的
    地址。

  • 您不能重新分配引用。一旦它被初始化,它指向同一对象的整个生命。

这篇关于指针和参考参数之间的差异?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆