Reference vs. pointer

前端 未结 6 515
终归单人心
终归单人心 2020-12-28 08:33

What is the difference? Because this:

int Value = 50;
int *pValue = &Value;

*pValue = 88;

and ref version do the same:



        
6条回答
  •  -上瘾入骨i
    2020-12-28 09:15

    In this case, they are equivalent.

    It does not matter which you use, and neither is "best".

    If you really want to choose between them then the reference is probably more idiomatic. I generally stick to references wherever I can because my OCD likes it: they feel "tighter", cannot be re-bound (with or without you noticing) and don't require a dereference to get to the value.

    But I'm not aware of any general consensus on the issue for cases such as this.

    Also note that the two may not compile to the same code if your implementation does not implement references with pointers, though I know of no implementation like that, and you wouldn't notice the difference anyway.

提交回复
热议问题