Pointers vs. References in C/C++

September 9th, 2009 Leave a Comment

Pointers and references are equally efficient because they are practically doing the same thing (see example below).

void FuncPtr(int * p)
{
   *p = *p - 3;
}

void FuncRef(int & r)
{
   r = r - 3;
}



There are several major differences between references and pointers.

  • Pointer uses operator -> to access member functions and variables, while a reference uses a dot (.), just like a regular object.
  • References can only be initialized once. A pointer can point to a certain object and then, at any time, be changed to point to a different object.
  • Unlike pointers, references must be initialized as soon as they are declared.
  • References cannot be NULL, but pointers can.
  • References cannot be deleted or newed like a pointer.

Now, let’s look at their advantages.

Advantages of using pointers over references are as follows.

  • We can change what a pointer points to and perform arithmetic operations with pointers. These are not possible with references.

Advantages of using references over pointers are as follows.

  • The reference syntax is simpler.
  • References are safe as they always point to a valid address, while pointers can be invalid and cause fatal errors due to uninitialized, out-of-bound addresses or wrong type-casting.
  • References are useful for copy constructors and overloaded operators.
  • Function parameters that are declared as constant references accept expressions as arguments while pointers and non-constant references require a variable.

Accessing a variable or object through a pointer or reference may be just as fast as accessing it directly (as most microprocessors are constructed this way).

However, there are disadvantages of using pointers and references (as follows).

  • They require an extra register to hold the value of the pointer or reference. If there are not enough registers then the pointer has to be loaded from memory each time it is used, which will make the program slower.
  • Before a pointer can be accessed, the value contained in a pointer register has to be read and subsequently used as an address to the memory. Therefore, this process needs a few clock cycles before the variable pointed to can be accessed.

Tags:
, , ,

Leave a Reply


+ seven = 15