liveBook · Manning

Rvalue reference

As explained in Learn C++ by Example

An rvalue reference is a C++ reference type, written with &&, that can bind to an rvalue.

An rvalue reference is a C++ reference type written with && that binds to an rvalue, such as the temporary vector returned by get_next_row. Passing that temporary to an appropriate overload lets a container move its contents instead of copying them. section 2.2.3

The distinction matters when choosing vector insertion operations:

  • push_back(const T&) copies a fully formed value into the vector. section 2.2.3
  • push_back(T&&) accepts an rvalue and can move it into the vector. section 2.2.3
  • A move constructor, written with an rvalue reference parameter, can take ownership of a temporary vector’s elements. section 2.2.3

Building a triangle without copying rows

generate_triangle initializes a triangle with {1}, then appends get_next_row(triangle.back()) for each row. Because get_next_row produces a temporary vector, push_back can move that row rather than copy it; emplace_back offers another in-place construction path. section 2.2.3

Listing 2.4 Moving a temporary
auto generate_triangle(int rows)
{
    std::vector<std::vector<int>> triangle{ {1} };    #1
    for (int row = 1; row < rows; ++row)              #2
    {
        triangle.push_back(get_next_row(triangle.back()));
    }
    return triangle;
}

A complete triangle-generation listing shows an rvalue-producing function passed directly to vector::push_back. section 2.2.3

How Learn C++ by Example covers it

How deep it goes
Explains lvalues, rvalues, overloads, and move construction, while deferring complete value-category details.
Examples
Uses temporary vectors, get_next_row, triangle generation, push_back overloads, and emplace_back.
What it assumes
Builds from the distinction between named lvalues and unnamed rvalues before applying reference overloads.
What you can do after
Apply it via vector insertion and move construction to avoid copying temporary vectors.
How it connects
Connects rvalue references with lvalues, move semantics, move constructors, push_back, emplace_back, and perfect forwarding.

Also explained in

Compare how 2 books explain rvalue reference →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn C++ by Example. The section links point to the parts of the book it draws on.