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

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

    You have many situations wherein a parameter does not exist or is invalid and this can depend on runtime semantics of the code. In such situations you can use a pointer and set it to NULL (0) to signal this state. Apart from this,

    • A pointer can be re-assigned to a new state. A reference cannot. This is desirable in some situations.
    • A pointer helps transfer owner-ship semantics. This is especially useful in multi-threaded environment if the parameter-state is used to execute in a separate thread and you do not usually poll till the thread has exited. Now the thread can delete it.

提交回复
热议问题