LearnFrenzy
Sign in Take a free test

C++ Programming · Topic 7 of 27

References: lvalue and rvalue

  • 4 exercises
  • 60 questions
  • ~60 min
  • Answers explained

Introduction & Syntax

References: lvalue and rvalue · Study material

References in C++ are alternative names for existing objects. Declared with &, a reference lets a function change the caller's variable, pass large objects without copying, and return access to an element – with none of the null checks and */-> syntax of pointers. Modern C++ adds rvalue references (&&), the foundation of move semantics, and forwarding references with std::forward for perfect forwarding in templates. "Reference vs pointer", "what is an lvalue and an rvalue" and "what does std::move do" are standard C++ interview questions. This page explains them with programs you can run, followed by 60 practice questions – 20 MCQs, 20 predict-the-output puzzles, 10 find-the-error programs and 10 complete programs – verified on a real C++ compiler.

On this page

  • Lvalue references: declaring, binding, aliasing; references vs pointers
  • const references and temporaries; reference parameters and return values
  • References in range-for loops and structured bindings; dangling references
  • Value categories, rvalue references and std::move
  • Forwarding references, std::forward, reference collapsing and std::ref

What is a reference?

A reference is declared with & after the type: int& r = x;. From then on r is x – reading, writing or taking the address of r works on x. A reference must be initialized when it is declared and can never be made to refer to another object: assigning to it assigns to the referred object.

#include <iostream>

int main() {
    int marks = 70;
    int& r = marks;          // r is another name for marks – must be initialized
    r += 15;                 // changes marks
    std::cout << marks << ' ' << r << ' ' << (&r == &marks) << '\n';

    int other = 5;
    r = other;               // NOT re-binding: assigns other's value to marks
    other = 99;
    std::cout << marks << ' ' << r << ' ' << other << '\n';
    return 0;
}

Output

85 85 1
5 5 99

References vs pointers

Reference T&Pointer T*
Must be initializedyesno (but should be)
Can be nullnoyes
Can be re-seatednoyes
Access syntaxlike the object: r.x*p, p->x
Arithmetic, arrays of themnoyes
Use forparameters, aliases, returning membersoptional objects, re-pointing, data structures

Reference parameters

A T& parameter lets the function modify the caller's object (an "out" or "in-out" parameter). A const T& parameter gives read-only access without copying, and – unlike T& – it can also bind to temporaries and literals. This is the standard way to pass strings, vectors and class objects.

#include <iostream>
#include <string>
#include <vector>

void apply_discount(double& price, double percent) { price -= price * percent / 100; }   // out-parameter
double total(const std::vector<double>& prices) {                                       // read-only, no copy
    double t = 0;
    for (double p : prices) t += p;
    return t;
}
void greet(const std::string& name) { std::cout << "Hi " << name << '\n'; }

int main() {
    double shoes = 2000;
    apply_discount(shoes, 25);
    std::vector<double> cart{shoes, 499.5, 250};
    std::cout << shoes << ' ' << total(cart) << '\n';
    greet("Asha");                    // const& binds to a temporary std::string
    return 0;
}

Output

1500 2249.5
Hi Asha

Returning references

A function may return a reference to something that outlives the call – a class member, an element of a container, or a parameter that was itself passed by reference. The caller can then read or assign through it (v.at(i) = 5). Providing a const overload returning const T& keeps const objects read-only. Never return a reference to a local variable.

#include <iostream>
#include <string>
#include <vector>

class Inventory {
    std::vector<int> stock_{5, 0, 12};
public:
    int& at(std::size_t i) { return stock_[i]; }                    // caller can modify the element
    const int& at(std::size_t i) const { return stock_[i]; }        // read-only version for const objects
    std::size_t size() const { return stock_.size(); }
};

int main() {
    Inventory inv;
    inv.at(1) = 40;                 // assigning to the returned reference
    ++inv.at(2);
    const Inventory& view = inv;
    for (std::size_t i = 0; i < view.size(); ++i) std::cout << view.at(i) << ' ';
    std::cout << '\n';
    return 0;
}

Output

5 40 13

References in loops and structured bindings

In a range-for loop, auto& modifies elements in place, const auto& reads them without copying, and plain auto works on copies. Structured bindings follow the same rule: auto& [k, v] : map lets you change the values.

#include <iostream>
#include <map>
#include <string>
#include <vector>

int main() {
    std::vector<std::string> names{"asha", "ravi", "meera"};
    for (auto& n : names) n[0] = static_cast<char>(n[0] - 32);     // auto& : modify in place
    for (const auto& n : names) std::cout << n << ' ';             // const auto& : read without copying
    std::cout << '\n';

    std::map<std::string, int> score{{"Asha", 80}, {"Ravi", 70}};
    for (auto& [name, s] : score) s += 5;                          // structured binding by reference
    for (const auto& [name, s] : score) std::cout << name << '=' << s << ' ';
    std::cout << '\n';
    return 0;
}

Output

Asha Ravi Meera
Asha=85 Ravi=75

Dangling references

A reference must not outlive its object. Returning a reference to a local, keeping a reference to a vector element across push_back (which may reallocate), or binding a reference to a member of a temporary all produce dangling references – undefined behaviour that may appear to work and then fail. A const& bound directly to a temporary extends that temporary's life to the reference's scope, but this does not apply through function returns.

int& bad() {
    int local = 5;
    return local;                   // dangling: local is destroyed when bad() returns
}

std::vector<int> v{1, 2, 3};
int& first = v[0];
v.push_back(4);                     // may reallocate → first now dangles
// use v[0] again instead of keeping the reference

const std::string& ok = std::string("temp");    // OK: lifetime extended to ok's scope
const std::string& bad2 = make_name().substr(1); // OK too – binds directly to the temporary

Value categories: lvalues and rvalues

Every expression is either an lvalue – something with a name and an identity you can take the address of (variables, *p, a[i]) – or an rvalue – a temporary value about to disappear (literals, x + 1, a function returning by value). An int& binds only to modifiable lvalues, a const int& binds to anything, and an int&& (rvalue reference) binds only to rvalues. Overload resolution uses this to tell temporaries apart.

#include <iostream>
#include <string>

void take(int&)        { std::cout << "lvalue& "; }
void take(const int&)  { std::cout << "const& "; }
void take(int&&)       { std::cout << "rvalue&& "; }

int make() { return 7; }

int main() {
    int x = 1;
    const int c = 2;
    take(x);            // named, modifiable object: lvalue
    take(c);            // const lvalue
    take(5);            // literal: rvalue
    take(x + 1);        // temporary result: rvalue
    take(make());       // returned by value: rvalue
    take(std::move(x)); // cast to rvalue
    std::cout << '\n';
    return 0;
}

Output

lvalue& const& rvalue&& rvalue&& rvalue&& rvalue&&
ArgumentT&const T&T&&
non-const lvalue (x)✔ best✔✘
const lvalue✘✔✘
rvalue (5, f(), x + 1)✘✔✔ best
std::move(x)✘✔✔ best

Rvalue references and std::move

Because an rvalue is about to be destroyed, a function receiving it through T&& may steal its resources instead of copying them – that is a move. std::move(x) does not move anything by itself: it is just a cast that says "treat x as an rvalue; I won't need its value". After a move, the source is left in a valid but unspecified state (strings and vectors become empty in practice) – assign to it before using it again.

#include <iostream>
#include <string>
#include <utility>
#include <vector>

int main() {
    std::string draft = "a long report text that we no longer need here";
    std::vector<std::string> archive;
    archive.push_back(draft);               // copies
    archive.push_back(std::move(draft));    // moves: steals the buffer, no copy
    std::cout << archive.size() << ' ' << archive[1].size() << ' ' << draft.empty() << '\n';

    std::string&& tmp = std::string("temporary") + "!";   // && extends the temporary's life
    tmp += "?";
    std::cout << tmp << '\n';
    return 0;
}

Output

2 46 1
temporary!?

Forwarding references and std::forward

In a template, T&& where T is deduced is a forwarding reference (also called a universal reference): it binds to both lvalues and rvalues. Inside the function the parameter has a name, so it is an lvalue; std::forward<T>(arg) restores the original category, passing rvalues on as rvalues. This is perfect forwarding, used by emplace_back, make_unique and every wrapper function.

#include <iostream>
#include <string>
#include <utility>

void sink(const std::string&) { std::cout << "copy "; }
void sink(std::string&&)      { std::cout << "move "; }

template <typename T>
void relay(T&& arg) {                 // T&& in a template: a forwarding (universal) reference
    sink(std::forward<T>(arg));       // keeps the argument's value category
}

template <typename T>
void relay_wrong(T&& arg) {
    sink(arg);                        // a named parameter is always an lvalue → always copies
}

int main() {
    std::string s = "text";
    relay(s);
    relay(std::string("tmp"));
    relay_wrong(std::string("tmp"));
    std::cout << '\n';
    return 0;
}

Output

copy move copy

Reference collapsing explains how it works: when T is deduced as U& (for an lvalue), T&& becomes U& &&, which collapses to U&. Only && && collapses to &&; any combination with & gives &.

std::ref and std::reference_wrapper

References are not objects, so containers cannot hold them and functions such as std::thread and std::bind copy their arguments. std::reference_wrapper<T> (created with std::ref / std::cref) is a copyable object that behaves like a reference.

#include <functional>
#include <iostream>
#include <thread>
#include <vector>

void add_ten(int& n) { n += 10; }

int main() {
    int a = 1, b = 2, c = 3;
    std::vector<std::reference_wrapper<int>> refs{a, b, c};   // containers can hold reference_wrapper
    for (int& r : refs) r *= 100;
    std::cout << a << ' ' << b << ' ' << c << '\n';

    int counter = 0;
    std::thread t(add_ten, std::ref(counter));                // std::ref passes by reference
    t.join();
    auto f = std::bind(add_ten, std::ref(counter));
    f();
    std::cout << counter << '\n';
    return 0;
}

Output

100 200 300
20

Common mistakes

  • Expecting r = y to re-bind a reference – it copies y into the referred object.
  • Returning a reference to a local or to a temporary – it dangles.
  • Keeping a reference to a vector element across push_back.
  • Binding int& to a literal – only const int& (or int&&) accepts temporaries.
  • Using an object after std::move without assigning a new value.
  • std::move on a const object – it silently copies, because a const object cannot be moved from.
  • Forgetting std::forward in a forwarding function – rvalues get copied.

Key points to remember

  • A reference is an alias: initialized once, never null, never re-seated.
  • T& modifies, const T& reads without copying and accepts temporaries.
  • Lvalues have identity; rvalues are temporaries.
  • T&& binds to rvalues and enables moving; std::move is only a cast.
  • In templates, T&& is a forwarding reference – pair it with std::forward.

Frequently asked questions

Are references just pointers in disguise?

Compilers often implement them with addresses, but the language treats a reference as the object itself: no null state, no re-seating, no arithmetic, and the compiler may optimise it away entirely.

When should I use a pointer instead of a reference?

When "no object" is a valid value (nullptr), when you need to point to different objects over time, or when building data structures such as linked lists and trees.

Does std::move make my code faster?

Only when the target type has a move constructor or move assignment that is cheaper than copying (strings, vectors, unique_ptr …), and only when you no longer need the source's value.

Where can I learn more?

Read C++ References and C++ Move Semantics, then practise with the exercises below.

Ready to test your Programming?

Timed online tests with instant scores and explanations.

About this section

About C++ Programming

C++ adds object-oriented programming, templates and the powerful Standard Template Library (STL) to C. It powers game engines, browsers, trading systems and most competitive programming. This section takes you from basic syntax to classes, inheritance, polymorphism, modern C++ (C++11 to C++23) and the STL – every concept with runnable examples and practice questions checked on a real compiler.

Why it matters

  • OOP concepts – classes, inheritance, polymorphism, encapsulation – are asked in almost every interview
  • C++ with the STL is the most popular language for competitive programming and DSA rounds
  • Questions on constructors, virtual functions, references and smart pointers decide technical rounds
  • Modern C++ skills are in demand at product companies, fintech and game studios

Who it is for

  • School students (Class 11–12 computer science with C++) preparing for board exams and practicals
  • College students (B.Tech, BCA, MCA) learning OOP and data structures for semester exams and labs
  • Freshers preparing for placements, coding tests and C++ technical interviews
  • Competitive programmers who want to master the STL

What every topic gives you

  • Study material in five tabs: concepts with runnable examples, coding techniques, programs, interview questions and a cheat sheet
  • MCQs that check your understanding of every concept
  • "Predict the output" puzzles – the trickiest part of written tests
  • "Find the error" programs that train you to spot bugs quickly
  • Complete programs with solutions and real output, verified on a compiler

Asked in

  • Campus placements
  • Product company interviews
  • Coding rounds & DSA
  • Competitive programming
  • GATE CS
  • University exams

How to use this section

  1. Read the study material of a topic and run the examples yourself.
  2. Practise the four exercises – MCQs, output, errors, programs – and read every explanation.
  3. Test yourself with the timed online test, then revise the topics you got wrong.

Search LearnFrenzy

Esc

Quick links