C++ Objects: When should I use pointer or reference

前端 未结 9 1436
情话喂你
情话喂你 2020-12-03 08:45

I can use an object as pointer to it, or its reference. I understand that the difference is that pointers have to be deleted manually, and references remain until they are o

9条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-03 09:06

    As my c++ teacher used to put it, pointers point to the memory location while references are aliases . Hence the main advantage is that they can be used in the same way as the object's name they refer to, but in a scope where the object is not available by passing it there.

    While pointers can be redirected to some other location, references being like constant pointers, can't be redirected. So references cant be used for traversing arrays in a functions etc.

    However a pointer being a separate entity takes up some memory, but the reference being the same as the referred object doesn't take any additional space. This is one of its advantages.

    I have also read that the processing time for references are less,

    as

    int & i = b ;

    i++ ; takes lesser time than

    int * j = b ;

    (*j) ++ ;

    but I am yet to confirm this. If anyone can throw light on this claim it would be great.

    Comments are welcome :)

提交回复
热议问题