Value and reference semantics
What you will learn on this page
Section titled “What you will learn on this page”- What it means that C++ types are copied by default, and why that is useful.
- The difference between a copy and a reference (another name for the same object).
- How to choose a parameter type: by value, by reference, or by reference to
const. - Why passing a derived object by value can silently lose part of it.
Copies by default
Section titled “Copies by default”In Java, Python, or C#, a variable of a class type holds a reference: assigning one variable to another makes both refer to the same object. C++ does the opposite by default. Assigning or passing an object makes a copy, a new object with the same value, unless you ask for a reference.
A type whose copies are independent has
value semantics. int,
std::string, and std::vector all behave this way, and so does a class built
from them. This one holds a list of titles:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// A value type: copying a Shelf gives an independent Shelf.// A Shelf is a list of book titles. It writes no copy code of its own, so// C++ generates it: copying a Shelf copies its std::vector, and copying// the vector copies every string in it. The copy shares nothing with the// original, so changing one never changes the other.class Shelf {public: // Adds one title at the end. `title` is the function's own string (it is // taken by value, so it was copied or built from the caller's argument), // so std::move hands its characters to the new vector element instead // of copying them again. void add(std::string title) { titles_.push_back(std::move(title)); } [[nodiscard]] std::size_t size() const noexcept { return titles_.size(); } // Lets callers read every title without copying the list: the result // is a const reference to the Shelf's own vector. It is a borrowed view, // not a copy, so it depends on the Shelf: // Valid only while this Shelf is alive and unchanged. [[nodiscard]] const std::vector<std::string>& titles() const noexcept { return titles_; }
private: std::vector<std::string> titles_;};Shelf declares no copy operations, so C++ generates them: copying a Shelf
copies its std::vector, which copies each string. Now compare a copy with a
reference:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
Shelf mine; // a new, empty Shelfmine.add("Persuasion");
// `=` with a new variable makes a copy: `copy` gets its own vector// holding its own "Persuasion" string.Shelf copy = mine; // a second, independent Shelfcopy.add("Emma"); // changes copy only: mine still has 1 title
// The `&` makes `alias` a reference, not a new Shelf. No copy is made,// and from now on alias and mine are two names for one object.Shelf& alias = mine; // another name for the same Shelfalias.add("Ivanhoe"); // so this adds to mine: now 2 titles
// mine: Persuasion, Ivanhoe. copy: Persuasion, Emma.std::cout << "mine: " << mine.size() << ", copy: " << copy.size() << '\n';The output begins with:
mine: 2, copy: 2copy started as a copy of mine (one title) and gained “Emma”: two titles.
alias is a reference, written Shelf&: another name for mine itself, not a
new object. Adding “Ivanhoe” through alias changed mine, which now also has two
titles. Adding to copy did not affect mine at all.
Text description of the diagram
Three names and two objects. The names mine and alias both lead to the same
Shelf object, which holds “Persuasion” and “Ivanhoe”. The name copy leads to a
second, separate Shelf object, which holds “Persuasion” and “Emma”. Changing the
object through either mine or alias changes the same object; changing copy
changes only the second one.
Diagram source (Mermaid)
flowchart LR
mine([name: mine]) --> A["Shelf object 1<br/>Persuasion, Ivanhoe"]
alias([name: alias]) --> A
copy([name: copy]) --> B["Shelf object 2<br/>Persuasion, Emma"]A reference must be bound to an object when it is created, and it can never be re-bound to another object or be null. It does not own the object or keep it alive: if the object is destroyed, the reference dangles (see the previous lesson).
Why value semantics is a design advantage
Section titled “Why value semantics is a design advantage”Values are easy to reason about. When a function receives a copy, nothing it does can surprise the caller, and nothing the caller does later can change the function’s copy. There is no question of who else might be changing the object, which matters even more once several threads are involved. That is why most standard containers and strings are value types, and why this site prefers them where they fit.
The cost is the copy itself. Copying a Shelf with thousands of titles copies
thousands of strings. Choosing parameter types is mostly about avoiding copies
that nobody needs, without giving up the safety of values where it matters.
Three ways to pass a parameter
Section titled “Three ways to pass a parameter”Here are three functions that take a Shelf in different ways:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// `inline` lets a function be defined in a header that several .cpp files// include, without a "defined more than once" error when they are linked.//// By value: the function gets its own copy; the caller's Shelf is untouched.// The copy is made when the function is called and destroyed when it// returns, so the "Draft" title exists only inside this function. Returns// the size of the copy: one more than the caller's Shelf.inline std::size_t size_after_adding_draft(Shelf shelf) { shelf.add("Draft"); return shelf.size();}
// By reference: the function works on the caller's Shelf and may change it.// `Shelf& shelf` makes `shelf` another name for the caller's object, so// both titles land on the caller's Shelf. Nothing is copied.inline void add_classics(Shelf& shelf) { shelf.add("Middlemarch"); shelf.add("Bleak House");}
// By reference to const: no copy, and no changes allowed.// Counts the titles that are at least `min_length` characters long. Only// const member functions (size, titles) can be called on `shelf` here;// a call to shelf.add(...) would not compile.inline std::size_t count_long_titles(const Shelf& shelf, std::size_t min_length) { std::size_t count = 0; // A range-for: visit each string in the vector, in order. `title` is a // const reference to each one in turn, so no string is copied. for (const std::string& title : shelf.titles()) { if (title.size() >= min_length) ++count; // size() is the number of characters } return count;}VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// mine holds 2 titles here: Persuasion and Ivanhoe.// By value: the function adds "Draft" to its own copy and returns 3;// mine is not touched and still has 2.std::cout << "by value returns " << lld::semantics::size_after_adding_draft(mine) << "; mine still has " << mine.size() << '\n';// By reference: the two classics are added to mine itself: 4 titles.lld::semantics::add_classics(mine);std::cout << "after add_classics, mine has " << mine.size() << '\n';// By const reference: reads mine without copying it. Titles with 10 or// more characters: Persuasion (10), Middlemarch (11), Bleak House (11,// the space counts). Ivanhoe (7) is too short, so the answer is 3.std::cout << "long titles: " << lld::semantics::count_long_titles(mine, 10) << '\n';How this code works: the three calls
Track mine, which holds two titles (Persuasion, Ivanhoe) when the calls start.
| Call | What the function works on | Result | mine afterwards |
|---|---|---|---|
size_after_adding_draft(mine) |
a fresh copy of mine |
3 | 2 titles |
add_classics(mine) |
mine itself |
(none) | 4 titles |
count_long_titles(mine, 10) |
mine itself, read only |
3 | 4 titles |
- By value. At the call, C++ copies
mineinto the parametershelf: a second vector with its own two strings. The function adds “Draft” to that copy and returns its size, 3. When the function returns, the copy is destroyed, and “Draft” with it.minenever saw it. - By reference.
shelfis bound tomine, so eachshelf.add(...)is reallymine.add(...). Nothing is copied, and both titles stay after the call:minenow holds Persuasion, Ivanhoe, Middlemarch, Bleak House. - By const reference. Again no copy, but the function may only read.
It visits each title and counts those with at least 10 characters:
Persuasion (10, counted, because the test is
>=), Ivanhoe (7, not counted), Middlemarch (11), and Bleak House (11, counting the space). The answer is 3.
The full output, including the lines from the next section:
mine: 2, copy: 2by value returns 3; mine still has 2after add_classics, mine has 4long titles: 3by reference: Your loan is overdueby value: Library notice- By value,
Shelf shelf. The function gets its own copy. It may change the copy freely (here, adding a draft title), and the caller’sminestill has two titles afterwards. The signature tells the caller: “I will not change your object.” - By reference,
Shelf& shelf. The function works on the caller’s object. Afteradd_classics(mine),minehas four titles. The signature tells the caller: “I may change your object.” It is a temporary borrow: the function uses the object during the call but does not keep or destroy it, so ownership stays with the caller. - By reference to const,
const Shelf& shelf. No copy, and the compiler rejects any attempt to change the object. The signature tells the caller: “I only read your object.” This is the usual choice for read-only access to anything bigger than a few numbers.
The signature is part of the design. A reader can tell, without reading the function body, whether a call can change their object.
A rule of thumb for parameters
Section titled “A rule of thumb for parameters”IllustrativeA fragment for explanation; not compiled on its own.
bool is_overdue(int days_late); // small and cheap: by valuevoid print_title(const Book& book); // read-only, not tiny: const&void add_classics(Shelf& shelf); // changes the caller's object: &Member::Member(std::string name) // keeps its own copy: by value, : name_(std::move(name)) {} // then moved into the member- Only reading, and the type is cheap to copy (built-in types such as
intanddouble, and small structs of a few such members): pass by value. - Only reading, and the type is not cheap to copy (strings, containers, most
classes): pass by
const&. - The function must change the caller’s object: pass by
&. Make this rare, because a function that changes its arguments is harder to follow than one that returns a result. - The function keeps its own copy (stores it in a member, for example), or
needs a modifiable copy anyway (and returns it): pass by value and then move it into place with
std::move, as in theMemberconstructor above. Moving transfers the contents instead of copying them; the move semantics lesson explains how. A parameter the function keeps is called a sink parameter.
Returning works differently: return results by value. Modern compilers build
a returned local object directly in the caller’s variable, or move it, so returning
a std::vector from a function does not copy its elements. Return a reference only
to something that outlives the call, such as Shelf::titles(), which refers to a
member of the Shelf. Its comment says the reference is valid only while the
Shelf is alive and unchanged.
Slicing: when a copy loses part of the object
Section titled “Slicing: when a copy loses part of the object”Value semantics has one trap with inheritance (covered fully in a later lesson).
Here a base class Notice has a derived class OverdueNotice that overrides
text(). Marking text() as virtual means a call through a Notice& runs the
version for the object’s real type; override marks the derived version that
replaces it. A class used this way, through a base class, is called
polymorphic.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// A base class: a general notice to a library member.class Notice {public: // A virtual destructor, so deleting an OverdueNotice through a Notice // pointer runs the right destructor (the inheritance lesson explains // why). `= default` means "the usual, generated body". virtual ~Notice() = default; // `virtual` means: when text() is called through a Notice& or Notice*, // run the version that belongs to the object's real type. [[nodiscard]] virtual std::string text() const { return "Library notice"; }};
// `: public Notice` makes OverdueNotice a kind of Notice: it has// everything a Notice has, and a Notice& or Notice* can refer to one.class OverdueNotice : public Notice {public: // `override` says "this replaces Notice::text"; the compiler checks // that there really is a virtual text() with the same signature to replace. [[nodiscard]] std::string text() const override { return "Your loan is overdue"; }};
// Takes a copy of the Notice part only: an OverdueNotice is sliced.// The parameter is a Notice object, with room for a Notice and no more.// Passing an OverdueNotice copies only its Notice part into it, so inside,// `notice` really is a plain Notice, and text() runs Notice::text().inline std::string describe_copy(Notice notice) { return notice.text(); }
// Refers to the caller's object, whatever its exact type.// Nothing is copied: `notice` is another name for the caller's// OverdueNotice, so the virtual call reaches OverdueNotice::text().inline std::string describe(const Notice& notice) { return notice.text(); }VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The same OverdueNotice is passed to both functions. describe takes// a const Notice&, so it sees the real object and the override runs.// describe_copy takes a Notice by value, so it gets a sliced copy and// prints the base-class text.const OverdueNotice overdue;std::cout << "by reference: " << lld::semantics::describe(overdue) << '\n';std::cout << "by value: " << lld::semantics::describe_copy(overdue) << '\n';The last two lines of the output above show the problem:
by reference: Your loan is overdueby value: Library noticedescribe_copy takes a Notice by value. A Notice variable has room for a
Notice and nothing more, so copying an OverdueNotice into it copies only the
Notice part. The copy is a plain Notice, and calling text() on it runs
Notice::text(). This is called
object slicing: the derived part is
“sliced off”. It compiles without a warning on GCC 11 and Clang 14 with the warnings
this site enables, and it is not undefined behaviour; the result is just not what
you intended.
describe takes a const Notice&, so it refers to the caller’s actual
OverdueNotice, and the override runs.
The design rule: pass and store objects of a polymorphic class (one meant to be used through a base class) by reference or pointer, never by value. The inheritance lessons show how to make a base class impossible to copy, so the compiler catches slicing for you.
Testing the behaviour
Section titled “Testing the behaviour”The tests pin down each behaviour this page relies on, including slicing:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// LLD_TEST and LLD_CHECK_EQ come from the site's test header lld_test.hpp// (explained with the first lesson's tests). size() returns std::size_t,// an unsigned type, so the expected values are written std::size_t{1} to// compare like with like.
// A copy, then a change to the copy: the original must still hold 1 title.LLD_TEST(copy_is_independent) { Shelf original; original.add("Persuasion"); Shelf copy = original; copy.add("Emma"); LLD_CHECK_EQ(original.size(), std::size_t{1}); LLD_CHECK_EQ(copy.size(), std::size_t{2});}
// A function that takes Shelf& must change the caller's object.LLD_TEST(reference_changes_the_original) { Shelf shelf; add_classics(shelf); LLD_CHECK_EQ(shelf.size(), std::size_t{2});}
// The function sees 1 title (its copy plus "Draft"), the caller still 0.LLD_TEST(by_value_parameter_leaves_caller_unchanged) { Shelf shelf; LLD_CHECK_EQ(size_after_adding_draft(shelf), std::size_t{1}); LLD_CHECK_EQ(shelf.size(), std::size_t{0});}
// Pins down slicing: the same object gives the derived text through a// reference and the base text through a by-value copy.LLD_TEST(passing_by_value_slices_a_derived_object) { const OverdueNotice overdue; LLD_CHECK_EQ(describe(overdue), std::string("Your loan is overdue")); LLD_CHECK_EQ(describe_copy(overdue), std::string("Library notice"));}When to choose values, and when references
Section titled “When to choose values, and when references”Prefer value semantics when:
- the object represents a value (a title, a date, a list of results), so copies being independent is what you want;
- the data is small, or copies are rare;
- you want to rule out surprises from shared changes, for example between threads.
Use references (or pointers, next lessons) when:
- the object has identity: there must be exactly one of it, such as the catalog or the member account, and code needs to work on that one object;
- copying would be expensive and the function only reads;
- the object is polymorphic, to avoid slicing.
Common mistakes
Section titled “Common mistakes”- Passing large objects by value just to read them. Each call copies the whole
object. Use
const&. - Passing by non-const reference “for speed”. If the function only reads, a
¶meter misleads readers and prevents passing temporary values. Useconst&. - Expecting Java-style sharing.
Shelf b = a;makes a copy; changingbnever changesa. - Passing polymorphic objects by value. The derived part is sliced off.
- Returning a reference to a local variable. The local is destroyed when the function returns, so the reference dangles. Return by value.
When a requirement changes
Section titled “When a requirement changes”New requirement: “Several librarians share one reading shelf, and each sees the others’ changes.”
That is a change from value to shared identity. Passing Shelf by value to each
librarian’s code would give everyone a private copy, which is exactly wrong now.
The design needs one Shelf object owned by something that outlives all the
librarians’ code, which each part refers to. Who owns that shared object, and for
how long, is the subject of the next lessons on ownership. The Shelf class
itself does not change; what changes is how the rest of the program holds it.
Exercise: Choose parameter types for six functions
Choose the parameter type for each function, and give a one-line reason.
print_title(Book book): prints a book’s title.days_between(Date from, Date to):Dateholds three small integers.Member(std::string name): a constructor that stores the name in a member.record_return(Loan loan): marks the caller’s loan as returned.send(Notice notice): sends any kind of notice, including derived types.normalized(std::string title): returns a trimmed, lower-case version of the title, leaving the caller’s string alone.
Show the explained answer
const Book&. It only reads, and aBookholds strings, so a copy is not cheap.Dateby value. ADateof three small integers is about as cheap to copy as a reference, and copies are easier to reason about.std::stringby value, thenstd::moveinto the member. It is a sink parameter: the constructor needs its own copy anyway. A caller passing a temporary pays only for a move.Loan&. It must change the caller’s object. (If you find yourself writing many such functions, ask whetherreturn_loan()should be a member function ofLoaninstead.)const Notice&.Noticeis polymorphic, so passing by value would slice derived notices down to the base.std::stringby value. The function needs a copy to modify anyway, so taking the parameter by value makes the copy at the call and lets the function change it freely.const std::string&plus a local copy inside the function also works, but it always copies, even when the caller passes a temporary.
For 1, std::string_view would be the choice if the function took only the title
string rather than the whole Book.
Summary
Section titled “Summary”- C++ copies objects by default; a reference is another name for an existing object.
- Value semantics (independent copies) makes code easier to reason about, at the cost of copying.
- Pass small values by value, larger read-only objects by
const&, objects the function must change by&, and sink parameters by value plusstd::move. - Return results by value; return references only to objects that outlive the call.
- Copying a derived object into a base-class value slices it; pass polymorphic objects by reference.