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

前端 未结 9 1422
情话喂你
情话喂你 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:11

    A reference is basically a pointer with restrictions (has to be bound on creation, can't be rebound/null). If it makes sense for your code to use these restrictions, then using a reference instead of a pointer allows the compiler to warn you about accidentally violating them.

    It's a lot like the const qualifier: the language could exist without it, it's just there as a bonus feature of sorts that makes it easier to develop safe code.

提交回复
热议问题