Double pointer vs pass by reference pointer

This question already has an answer here:

  • When to use references vs. pointers 17 answers
  • Are there benefits of passing by pointer over passing by reference in C++? 6 answers

  • "Why using reference to pointer instead of pointer to pointer"? You will get the same answer as if asking "why using pointer instead of reference" for any other kind of variable...

    Basically:

  • references (to pointer or any other variable) are smart because there should always be an object behind

  • pointers (to pointer or any other variable) are smart because they could possibly be NULL (optional)

  • references (to pointer or any other variable) are not available in C

  • references (to pointer or any other variable) are smart because they can be used as objects (no need to dereference like pointers, easier syntax, rading)

  • etc...

  • There are many posts answering this question already:

    What are the differences between a pointer variable and a reference variable in C++?

    Are there benefits of passing by pointer over passing by reference in C++?


    In that case the double pointer idiom is a C inheritance. C had no concept of references (and still has none) so the only way to modify a pointer was to pass a pointer to pointer.

    But as C++ offers references, you should use them when you only need to change a variable in a function, be it a pointer or not as it allow code to be more clear about programmer intentions.

    The exception to be above rule if when you want to use the null value as a special case (a reference can never point to null)


    The "pointer to pointer" idiom dates back to C, where it was necessary. C didn't have references. You're right to suspect it's not needed in C++.

    (A "double pointer" might also refer to double* , BTW, pointer-to-pointer isn't so ambiguous)

    链接地址: http://www.djcxy.com/p/20720.html

    上一篇: 总是通过引用传递一个不好的做法?

    下一篇: 双指针vs通过引用指针传递