When to use references vs. pointers

前端 未结 17 2142
一向
一向 2020-11-22 02:27

I understand the syntax and general semantics of pointers versus references, but how should I decide when it is more-or-less appropriate to use references or pointers in an

17条回答
  •  遥遥无期
    2020-11-22 03:24

    Disclaimer: other than the fact that references cannot be NULL nor "rebound" (meaning thay can't change the object they're the alias of), it really comes down to a matter of taste, so I'm not going to say "this is better".

    That said, I disagree with your last statement in the post, in that I don't think the code loses clarity with references. In your example,

    add_one(&a);
    

    might be clearer than

    add_one(a);
    

    since you know that most likely the value of a is going to change. On the other hand though, the signature of the function

    void add_one(int* const n);
    

    is somewhat not clear either: is n going to be a single integer or an array? Sometimes you only have access to (poorly documentated) headers, and signatures like

    foo(int* const a, int b);
    

    are not easy to interpret at first sight.

    Imho, references are as good as pointers when no (re)allocation nor rebinding (in the sense explained before) is needed. Moreover, if a developer only uses pointers for arrays, functions signatures are somewhat less ambiguous. Not to mention the fact that operators syntax is way more readable with references.

提交回复
热议问题