difference between a pointer and reference parameter?

Are these the same:

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

and

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

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 ?

Does this slice anything:

bar& ref = *ptr_to_bar;

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.

A few more differences:

  • You can't assign NULL to a reference. This is a crucial difference and the main reason you'd prefer one over the other.
  • When you take the address of a pointer, you get the address of the pointer variable. When you take the address of a reference, you get the address of the variable being referred to.
  • You can't reassign a reference. Once it is initialized it points to the same object for its entire life.

  • Ignoring every syntactic sugar and possibilities that can be done with the one and not with the other and difference between pointers and references explained in other answers (to other questions) ... Yeah those two are functionally exactly the same! Both call the function and both handle virtual functions equally well.

    And no, your line does not slice. It's just binding the reference directly to the object pointed to by a pointer.

    Some questions on why you would want to use one over the other:

  • Difference between pointer and reference
  • Are there any benefits of passing by pointer over reference?
  • Pointer vs. Reference
  • Instead of trying to come up with differences myself, i delegate you to those in case you want to know.


    Reference is a constant pointer ie, you can't change the reference to refer to other object. If you change, value of the referring object changes.

    For Ex:

           int j = 10;
           int &i = j;
           int l = 20;
           i = l; // Now value of j = 20
    
           int *k = &j;
           k = &l;   // Value of j is still 10
    
    链接地址: http://www.djcxy.com/p/20724.html

    上一篇: C ++函数参数:使用引用还是指针(然后解引用)?

    下一篇: 指针和参考参数之间的区别?