Sahaj.blogs
17 Nov 2023 · StudyPhase 2 · C++

C++ · References

References as aliases, pass-by-value vs pass-by-reference, and const references for passing big objects cheaply.

A reference (int& r = x;) is an alias: a second name for an existing variable. Unlike a pointer:

  • it must be initialised and can’t be null
  • it can’t be re-pointed to another variable
  • there’s no * to dereference it; you just use it like the variable

How references change function calls:

signaturethe function getscan change the caller’s value?copies?
f(std::string s)a copynoyes
f(std::string& s)the originalyesno
f(const std::string& s)the original, read-onlynono

The C++ Core Guidelines advise passing cheap types (int, double) by value and bigger ones by const&.

#include <iostream>
#include <string>

void byValue(std::string s)        { s += "!"; }
void byRef(std::string& s)         { s += "!"; }
std::size_t length(const std::string& s) { return s.size(); }   // no copy, no change

void swapInts(int& a, int& b) { int t = a; a = b; b = t; }

int main() {
    int x = 1;
    int& r = x;
    r = 99;
    std::cout << "x=" << x << '\n';

    std::string msg = "hello";
    byValue(msg); std::cout << msg << '\n';
    byRef(msg);   std::cout << msg << '\n';
    std::cout << "length " << length(msg) << '\n';

    int a = 3, b = 8;
    swapInts(a, b);
    std::cout << "a=" << a << " b=" << b << '\n';
}

Output:

x=99
hello
hello!
length 6
a=8 b=3

#cpp#references

Sources

  1. Reference declaration — cppreference.com
  2. Pass by lvalue reference — LearnCpp.com
  3. C++ Core Guidelines F.16: pass cheap types by value, others by const reference — Standard C++ Foundation