When to use references vs. pointers

前端 未结 17 2434
一向
一向 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:22

    My rule of thumb is:

    • Use pointers for outgoing or in/out parameters. So it can be seen that the value is going to be changed. (You must use &)
    • Use pointers if NULL parameter is acceptable value. (Make sure it's const if it's an incoming parameter)
    • Use references for incoming parameter if it cannot be NULL and is not a primitive type (const T&).
    • Use pointers or smart pointers when returning a newly created object.
    • Use pointers or smart pointers as struct or class members instead of references.
    • Use references for aliasing (eg. int ¤t = someArray[i])

    Regardless which one you use, don't forget to document your functions and the meaning of their parameters if they are not obvious.

提交回复
热议问题