bhylu.com

Advertisements

C++ References

Change a caller-owned count through a reference and use const references for read-only larger objects.

How it works

A reference is an alias bound to an existing object. It is normally used to express a required borrowed argument; it does not own or extend the lifetime of an arbitrary referenced object. Passing a const reference avoids copying a larger object and prevents mutation through that parameter. Returning a reference can be useful only when its target outlives every permitted use. For small numeric values, passing by value is often clearer than creating unnecessary reference contracts.

Run it locally

Use a C++20 compiler and matching standard library in a separate lab folder. The command uses c++; substitute g++, clang++ or zig c++ for your toolchain. C++ does not currently run in Bhylu’s browser playground. Apache, PHP and MySQL are not needed.

c++ -std=c++20 -Wall -Wextra -Wpedantic -Werror references.cpp -o lesson

On Windows use -o lesson.exe and run .\lesson.exe in PowerShell. On Unix-like systems run ./lesson. Thread examples may need -pthread on your platform.

Download the complete C++ source. Run file labs in a private empty directory, away from existing reports.

Example

C++20 · references.cpp

#include <iostream>
#include <string>

void add_parcel(int& count) { ++count; }
void print_round(const std::string& name) { std::cout << "Round: " << name << '\n'; }

int main() {
    int parcels{6};
    add_parcel(parcels);
    std::string name{"West round"};
    print_round(name);
    std::cout << "Parcels: " << parcels << '\n';
}

Expected result

Round: West round
Parcels: 7

The count reference aliases the initialized int in main, whose small value can be incremented safely. The string reference reads the caller’s live text without retaining it. The ampersand in a declaration forms a reference type; in an expression it can be an address-of operator. Context determines its role.

Consult the WG21 C++ working group and the C++ Core Guidelines for language references and design guidance. Check the selected standard version and your implementation’s library support.