Skip to content

Module 3 · Functions and References — topic 5 of 5

References

A reference is an alias for an existing object. Learn lvalue references, const references, how they differ from pointers, and rvalue references for move semantics.

Beginner 14 min read·Lesson 12 of 40 in C++ Programming

Learning objectives

  • Declare and use lvalue and const references
  • Compare references with pointers
  • Recognise rvalue references and std::move

Definition

A reference is an alias — another name — for an existing object. It must be initialised when declared, cannot be reseated to refer to a different object, and cannot be null.

Introduction

int& r = x; makes r another name for x. Anything done to r is done to x. There is no separate object, no * to dereference and no address arithmetic.

References are how C++ passes large objects efficiently and how operators like = and << return objects so they can be chained.

Why it matters

References remove many pointer bugs: they can't be null and can't be accidentally re-pointed.

Move semantics (rvalue references) are why returning a vector by value is cheap in modern C++.

Detailed explanation

lvalue reference T& binds to a named, modifiable object. const reference const T& binds to anything, including temporaries: const std::string& s = "hi"; extends the temporary's lifetime.

Reference vs pointer: a pointer is an object holding an address; it can be null, re-pointed and needs * / ->. A reference is an alias; it is always bound and uses normal syntax.

A reference to an object that no longer exists is dangling — e.g. returning a reference to a local variable. Using it is undefined behaviour.

rvalue reference T&& binds to temporaries. Move constructors take T&& and steal resources instead of copying. std::move(x) casts x to an rvalue to allow moving from it.

Syntax

C++
int x = 10;
int& alias = x; // alias for x
const int& view = x; // read-only alias
alias = 20; // x is now 20
std::string a = "long text";
std::string b = std::move(a); // b takes a's buffer; a is valid but unspecified
  • & in a declaration means reference; in an expression it means address-of.
  • References can't be reseated: alias = y; assigns y's value to x.
  • After std::move, only assign to or destroy the moved-from object.

Code examples

An alias

C++
#include <iostream>
int main() {
int score = 70;
int& s = score;
s += 15;
std::cout << score << ' ' << (&s == &score) << '\n';
return 0;
}
Output
85 1

Swap with references

C++
#include <iostream>
void swap_values(int& a, int& b) {
int t = a;
a = b;
b = t;
}
int main() {
int x = 3, y = 9;
swap_values(x, y);
std::cout << x << ' ' << y << '\n';
return 0;
}
Output
9 3

More examples

Returning references and moving

C++
#include <iostream>
#include <string>
#include <utility>
#include <vector>
int& largest(std::vector<int>& v) {
int* best = &v[0];
for (int& x : v) if (x > *best) best = &x;
return *best; // refers into v, which outlives the call
}
int main() {
std::vector<int> v{4, 19, 7};
largest(v) = 0; // modify the element through the returned reference
std::cout << v[0] << ' ' << v[1] << ' ' << v[2] << '\n';
std::string a = "a long string that owns heap memory";
std::string b = std::move(a);
std::cout << b.size() << ' ' << (a.empty() ? "a is empty" : "a still has data") << '\n';
return 0;
}
Output
4 0 7
35 a is empty

Step-by-step explanation

  • largest returns a reference to the biggest element, so the caller can assign to it.
  • This is safe because the vector belongs to the caller and outlives the call.
  • std::move(a) lets b take over a's buffer instead of copying 35 characters.
  • The standard only guarantees a moved-from string is valid; in practice (libstdc++/libc++) it is empty.

Expected output

Running “Returning references and moving” prints exactly:

TextOutput
4 0 7
35 a is empty

Practical applications

  • operator<< returns std::ostream& so cout << a << b chains.
  • Range-for loops use auto& to modify container elements.
  • Move semantics make containers of large objects efficient.

Best practices

  • Prefer references to pointers when null is not a valid value.
  • Never return references to locals.
  • Use std::move only when you no longer need the source.

Common mistakes

Uninitialised reference

Avoid

int& r;

Prefer

int x = 0;
int& r = x;

A reference must be bound when it is declared.

Binding a non-const reference to a temporary

Avoid

int& r = 5;

Prefer

const int& r = 5;

Only const references (or rvalue references) can bind to temporaries.

Important notes

  • The exact state of a moved-from standard library object is “valid but unspecified”; the example's "a is empty" reflects common implementations, not a guarantee.
  • Forwarding references (T&& in templates) and std::forward are an advanced extension of these ideas.

Key takeaways

  • A reference is an alias that can't be null or reseated.
  • const T& binds to anything and avoids copies.
  • T&& and std::move enable cheap moves.

Try it yourself

  1. 1
    Write void scale(std::vector<double>& v, double k) using a reference range-for.
  2. 2
    Show with a program that assigning to a reference changes the original rather than re-binding.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

9 questions test this exact topic. Answers and explanations are revealed after you submit.

  • BeginnerWhat is printed?
  • BeginnerWhich statement about references is true?
  • BeginnerWhy doesn't `int& r = 5;` compile?
Practise this topic