C++ copies by default
The objective of this lesson is to predict, for any line of C++, whether it makes a copy or creates an alias, and to pick the parameter type that says what a function does with its argument.
Python and Java give you references to objects almost everywhere. C++ does the opposite: a variable is the object, and assignment, initialisation and pass-by-value copy it. auto copy = v; on a std::vector allocates a new buffer and copies every element. To share an object you must ask for it explicitly with a reference (T&) or a pointer (T*).
- A value
T xowns its own storage. Changing it never affects anything else. - A reference
T& r = x;is another name for an existing object. It must be initialised, can never be null, and can never be re-pointed ("reseated") at a different object. Assigning torassigns tox. - A pointer
T* p = &x;is an object that holds an address. It can be null (nullptr), can be reseated, and must be dereferenced (*p,p->member) to reach the object.
#include <iostream>
#include <vector>
void by_value(int x) { x += 1; }
void by_ref(int& x) { x += 1; }
void by_ptr(int* x) {
if (x != nullptr) *x += 1;
}
int main() {
int a = 10;
by_value(a);
std::cout << "after by_value: " << a << '\n';
by_ref(a);
std::cout << "after by_ref: " << a << '\n';
by_ptr(&a);
std::cout << "after by_ptr: " << a << '\n';
by_ptr(nullptr); // allowed, and handled
std::vector<int> v{1, 2, 3};
std::vector<int> copy = v; // a new vector with its own buffer
std::vector<int>& ref = v; // another name for v
copy.push_back(4);
ref.push_back(5);
std::cout << "v: ";
for (int x : v) std::cout << x << ' ';
std::cout << "\ncopy: ";
for (int x : copy) std::cout << x << ' ';
std::cout << '\n';
}
Output (compiled with c++ -std=c++20 -O2 -Wall):
after by_value: 10
after by_ref: 11
after by_ptr: 12
v: 1 2 3 5
copy: 1 2 3 4
The same rule bites in range-for loops. for (auto o : orders) copies each element into o, so writing to o changes nothing and copying large elements costs time. Write for (const auto& o : orders) to read and for (auto& o : orders) to modify.
Choosing a parameter type
A function signature is documentation. The convention most C++ codebases (and interviewers) expect:
| Parameter | Meaning | Use for |
|---|---|---|
T x | the function gets its own copy | small, cheap types (int, double, pointers, small structs), or when the function would copy anyway |
const T& x | read-only access, no copy | large types you only read: std::string, std::vector, an Order struct |
T& x | the function modifies the caller's object | out-parameters and in-place updates |
T* x | optional object: nullptr means "none" | "may be absent", or interop with C APIs |
A const T& parameter also binds to temporaries (f(std::string("ESZ6")) works), while a plain T& does not. Returning a pointer (or std::optional) is the idiomatic way to say "lookup may fail"; returning a reference promises that the object exists.
Two facts that come up in interviews:
- A reference is not an object and has no address of its own;
sizeof(T&)issizeof(T). In practice the compiler implements a reference parameter as a pointer, so passingconst T&costs one address, not a copy. - For
intordouble,const T&is not faster thanT: the value fits in a register, and a reference forces the callee to load through memory and worry about aliasing. Pass small types by value.
const applies to the thing on its left
Read pointer declarations right to left. const qualifies what is immediately to its left (or, if nothing is to its left, what is immediately to its right).
#include <iostream>
struct Position {
int qty = 0;
int get() const { return qty; } // const member: callable on a const Position
void add(int q) { qty += q; } // non-const: needs a mutable Position
};
int main() {
int x = 1, y = 2;
const int* p1 = &x; // pointer to const int: *p1 is read-only
p1 = &y; // fine: the pointer itself can move
int* const p2 = &x; // const pointer to int: p2 cannot be reseated
*p2 = 10; // fine: the int it points to can change
// *p1 = 3; // error: read-only variable is not assignable
// p2 = &y; // error: cannot assign to variable 'p2' with const-qualified type
const Position pos{5};
// pos.add(1); // error: 'add' is not marked const
std::cout << *p1 << ' ' << x << ' ' << pos.get() << '\n'; // prints: 2 10 5
}
The three commented-out lines are rejected by the compiler with the errors shown (clang 17). const correctness means marking every reference parameter and member function const unless it must modify state. It documents intent, lets const objects call your methods, and turns accidental writes into compile errors. A const member function cannot modify members (except those declared mutable, which is how a const getter can lock a mutex or fill a cache).
Worked example
design the signatures for an order book helper
You hold a std::vector<Order> where Order has an id, a symbol string, a price and a qty. Write three functions: one that computes an order's notional, one that reduces an order's quantity after a fill, and one that finds an order by id when it may not exist. Choose each parameter and return type and justify it.
Show solutionHide solution
notionalonly reads, andOrdercontains astd::string, so a copy would allocate. Takeconst Order&.fillmust change the caller's order, so takeOrder&. The fill size is anint, so pass it by value.findmay fail. ReturningOrder&would force us to throw or invent a sentinel; returningOrder*letsnullptrmean "not found". It takes the vector by non-const reference because the caller will modify the order through the returned pointer.
#include <iostream>
#include <string>
#include <vector>
struct Order {
long id;
std::string symbol;
double price;
int qty;
};
// Read-only access to a large object: const reference, no copy.
double notional(const Order& o) { return o.price * o.qty; }
// Must modify the caller's object: non-const reference.
void fill(Order& o, int filled) { o.qty -= filled; }
// "Might not exist": pointer, nullptr means not found.
Order* find(std::vector<Order>& book, long id) {
for (Order& o : book)
if (o.id == id) return &o;
return nullptr;
}
int main() {
std::vector<Order> book{{1, "ESZ6", 5000.25, 10}, {2, "NQZ6", 18000.5, 3}};
if (Order* o = find(book, 2)) {
fill(*o, 1);
std::cout << o->symbol << " qty " << o->qty << " notional " << notional(*o) << '\n';
}
if (find(book, 99) == nullptr) std::cout << "order 99 not found\n";
}
Output:
NQZ6 qty 2 notional 36001
order 99 not found
Check: after the fill the quantity is and the notional is . Note the loop variable in find is Order& o; with Order o the function would return the address of a loop-local copy, which dies at the end of each iteration.
Dangling references and pointers
A reference or pointer does not keep its object alive. When the object's lifetime ends, every reference and pointer to it dangles, and using it is undefined behaviour: the program may print the old value, garbage, or crash, and the optimiser is allowed to assume it never happens.
The three classic sources:
- Returning a reference or pointer to a local. The local is destroyed when the function returns. Clang catches the simple case with
-Wall:
const std::string& label() {
std::string s = "local";
return s; // warning: reference to stack memory associated with local variable 's' returned
}
- Container reallocation. A
std::vectorstores elements in one contiguous buffer. Whenpush_backexceeds the capacity it allocates a larger buffer, moves the elements and frees the old one, so every pointer, reference and iterator into the old buffer dangles:
#include <iostream>
#include <vector>
int main() {
std::vector<int> v{1, 2, 3};
const int* before = v.data();
std::cout << "capacity before: " << v.capacity() << '\n';
v.push_back(4);
std::cout << "capacity after: " << v.capacity() << '\n';
std::cout << (before == v.data() ? "same buffer" : "buffer moved") << '\n';
}
capacity before: 3
capacity after: 6
buffer moved
(The growth factor is implementation-defined; libc++ doubled here.) So int& first = v[0]; v.push_back(x); use(first); is a bug even though it often appears to work.
- Views of temporaries.
std::string_view sv = std::string("ESZ6") + "C";points into a temporary string destroyed at the end of the statement.
nullptr. Use nullptr, not 0 or NULL, for a null pointer. It has its own type (std::nullptr_t), converts to any pointer type and never to int, so overloads like f(int) and f(char*) resolve as you expect. Dereferencing a null pointer is undefined behaviour, not a guaranteed crash; check before you dereference whenever null is a legal value.
Knowledge check
int a = 1; int& r = a; r = 5; int b = r; b = 7; int* p = &b; *p += 1; What does printing a and b give?
Knowledge check
Given double x = 1, y = 2; const double* p = &x; which statement compiles?
Knowledge check
std::vector<Order> orders{{10}, {20}}; for (auto o : orders) o.qty = 0; What is orders[0].qty + orders[1].qty afterwards?
Key takeaways
- Assignment, initialisation and pass-by-value copy in C++. Aliasing needs an explicit
&or*. - Pass small types by value, large read-only objects by
const T&, objects you modify byT&, and "may be absent" asT*. const T*is a pointer to const data;T* constis a const pointer. Mark member functionsconstwhen they do not modify the object.- References and pointers never extend lifetimes. Returning one to a local, or holding one across a
vectorreallocation, dangles. - Use
nullptr, and treat dereferencing null as undefined behaviour, not as a guaranteed crash.
Finished reading?
Answer the 3 knowledge checks to complete this lesson (0 done).