Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 out of scope.

When should I use each of them? What is the practical difference?

Neither of these questions answered my doubts:

  • Pointer vs. Reference
  • C++ difference between reference, objects and pointers
like image 822
rafaelxy Avatar asked Nov 26 '10 19:11

rafaelxy


2 Answers

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.

like image 156
suszterpatt Avatar answered Nov 03 '22 16:11

suszterpatt


"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.

like image 30
Steve Jessop Avatar answered Nov 03 '22 15:11

Steve Jessop