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

前端 未结 9 1401
情话喂你
情话喂你 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.
    0 讨论(0)
  • 2020-12-03 09:29

    suszterpatt already gave a good explanation. If you want a rule of thumb that is easy to remember, I would suggest the following:

    If possible use references, use pointers only if you can not avoid them.

    Even shorter: Prefer references over pointers.

    0 讨论(0)
  • 2020-12-03 09:31

    "pointers I have to delete and reference they remain until their scope finish."

    No, that's completely wrong.

    Objects which are allocated with new must be deleted[*]. Objects which are not allocated with new must not be deleted. It is possible to have a pointer to an object that was not allocated with new, and it is possible to have a reference to an object that was allocated with new.

    A pointer or a reference is a way of accessing an object, but is not the object itself, and has no bearing on how the object was created. The conceptual difference is that a reference is a name for an object, and a pointer is an object containing the address of another object. The practical differences, how you choose which one to use, include the syntax of each, and the fact that references can't be null and can't be reseated.

    [*] with delete. An array allocated with new[] must be deleted with delete[]. There are tools available that can help keep track of allocated resources and make these calls for you, called smart pointers, so it should be quite rare to explicitly make the call yourself, as opposed to just arranging for it to be done, but nevertheless it must be done.

    0 讨论(0)
提交回复
热议问题