CS 70

Reference Types

  • Pig speaking

    I loved arrays! Give me MORE!

  • LHS Cow speaking

    Okay. Are you ready for some new syntax?

  • Pig speaking

    MORE C++ syntax? I'll devour it!

A reference is another name for an existing piece of data. In this code, x and z are two names for the same thing!

int  x = 5;
int& z = x;

The & means “reference to”, and we read the second line (outwards from z) as "z is a reference to an int". We're not referring to a particular integer value (e.g., 5), we're referring to a storage location that already exists and can hold an int, specifically, the same location in memory used for x. (We can say that x is z's referent.)

Here's how we would represent this reference in our memory model:

New Diagram Rules

  • When a function is called, allocate space for all local variables except references (because the references refers to things that were already allocated).
  • When a reference is initialized, write its name next to its referent.
  • When a reference is destroyed, cross out its name (the referent and reference might not be destroyed at the same time!)
  • Dog speaking

    Creating a reference doesn't take up any memory?!? Awesome!!

  • Bjarne speaking

    In essence, yes. References do not consume any memory that you are allowed to access.

  • LHS Cow speaking

    In practice, behind the scenes, at least some of the time, the system probably does need to use some memory to make references work, but it's an under-the-hood how-C++-works-inside detail.

  • RHS Cow speaking

    In a later lesson we'll see how references probably work!

  • LHS Cow speaking

    We won't draw it in our diagram because we can't actually access or interact with that under-the-hood data.

  • RHS Cow speaking

    Logically, a reference is an alias (another name for existing data). That's how we'll model it.

(When logged in, completion status appears here.)