19 Oct 2026
Value Semantics
A quick-reference guide based on Klaus Iglberger's Back to Basics: Value Semantics (CppCon 2022), covering inheritance, polymorphism, references, const correctness, STL containers, and value-based abstractions.
(This is a recall of my LLM conversation so I can keep the concepts I learnt in the lecture)
1. Inheritance, Polymorphism, and Virtual Functions
1.1 virtual enables runtime polymorphism; = 0 makes a function pure virtual
class Shape {
public:
virtual ~Shape() = default;
virtual void accept(ShapeVisitor const&) = 0;
};
virtual allows derived classes to override the function. = 0 makes it pure virtual, meaning Shape is abstract and cannot be instantiated directly.
1.2 override is optional, but provides compile-time verification
class Circle : public Shape {
public:
void accept(ShapeVisitor const&) override;
};
The function overrides Shape::accept() even without override. The keyword simply makes the compiler verify that a matching virtual function exists in a base class. (In the case where you create an accept function with a different function signature than the actual virtual accept and are now none the wiser).
1.3 Member functions can be implemented inside or outside a class
// Implementation inside the class
class A {
public:
void f() { /* implementation */ }
};
// Implementation outside the class
class B {
public:
void f();
};
void B::f() { /* implementation */ }
Both are valid. An out-of-class definition requires a declaration inside the class first.
1.4 Pointers and virtual functions introduce indirection
std::vector<std::unique_ptr<Shape>> shapes;
shapes.emplace_back(std::make_unique<Circle>(2.0));
The vector holds pointers rather than actual shapes. Accessing objects requires pointer indirection, and virtual calls usually require dynamic dispatch. Separate heap allocations may worsen cache locality.
2. std::variant — Value-Based Polymorphism
2.1 std::variant stores different types by value without inheritance
using Shape = std::variant<Circle, Square>;
std::vector<Shape> shapes;
shapes.emplace_back(Circle{2.0});
shapes.emplace_back(Square{1.5});
for (auto const& s : shapes) {
std::visit(Draw{}, s);
}
std::variant stores one of its specified types directly within its own storage. std::visit invokes the appropriate overload of Draw for the active type.
Unlike unique_ptr<Shape>, individual shapes need no separate heap allocation or common base class. The variant's storage is large enough for its largest alternative, plus bookkeeping for the active type.
3. References, Pointers, and const Correctness
3.1 T passes by value; T& accesses the original object
void byValue(std::vector<int> v) {
v.clear(); // Original unaffected
}
void byRef(std::vector<int>& v) {
v.clear(); // Original modified
}
Passing by value creates a separate parameter object (typically copied or moved from the argument). Passing by reference avoids copying and allows modification of the original object.
3.2 const T& avoids copying while preventing mutation through the reference
void f(std::vector<int> const& v) {
std::cout << v.size(); // OK
// v.push_back(5); // Compilation error
}
The function accesses the original vector without copying it, but cannot modify it through v.
3.3 const T& and T const& mean exactly the same thing
void f(const Shape& s);
void g(Shape const& s);
Both are references to a const Shape. You can place const on either side of the type name.
Shape& const is invalid because references cannot be reseated.
3.4 Pointer const placement determines what can be modified
int a = 1, b = 2;
int* p = &a; // Mutable pointer, mutable int
const int* q = &a; // Mutable pointer, const int
int* const r = &a; // Const pointer, mutable int
const int* const s = &a; // Const pointer, const int
const before * prevents mutation of the pointed-to object through the pointer. const after * prevents reassigning the pointer itself.
3.5 A pointer to const does not necessarily make the original object immutable
int x = 10;
const int* p = &x;
// *p = 20; // Compilation error
x = 20; // OK
const int* restricts modification through p, not through other mutable access paths to x.
3.6 Violating const through ordinary operations produces compile-time errors
const std::vector<int> v{1, 2, 3};
// v[0] = 99; // Error
// v.push_back(4); // Error
// v.clear(); // Error
The compiler rejects operations that attempt to modify a const vector through its normal interface.
3.7 T&& is an rvalue reference, commonly used with move semantics
void consume(std::vector<int>&& v);
consume(std::vector<int>{1, 2, 3});
std::vector<int> x{4, 5, 6};
consume(std::move(x));
T&& can bind to temporary objects or objects explicitly cast to rvalues using std::move. std::move itself does not move anything; it enables move-aware operations.
3.8 Member-function const restricts mutation; noexcept restricts exception propagation
class Circle {
double radius;
public:
double getRadius() const noexcept {
return radius;
}
};
const prevents modifying non-mutable members through this. noexcept promises no exception will escape the function; if one does, std::terminate() is called.
4. std::span — A Non-Owning View
4.1 std::span typically stores a pointer and size; const on the span does not protect its elements
std::span<int> const s{v};
std::span is a non-owning view of contiguous elements, typically represented by a pointer and length. Here, const applies to the span object's metadata, not the integers it refers to.
Consequently, s[2] = 99 is valid. To prevent element modification through the span, use std::span<const int>.
5. STL Containers, Iterators, and Algorithms
5.1 STL containers use value semantics: copying creates independent elements
std::vector<int> a{1, 2, 3};
std::vector<int> b = a;
b[0] = 99;
// a = {1, 2, 3}
// b = {99, 2, 3}
Copying a vector copies its elements into independent storage. For vector<int>, modifying one vector does not affect the other.
5.2 A const std::vector prohibits insertion, deletion, and element mutation
const std::vector<int> v{1, 2, 3};
int x = v[0]; // OK
// v[0] = 5; // Error
// v.push_back(4); // Error
// v.erase(v.begin()); // Error
A const vector preserves its contents through its normal interface, preventing modifications to its size and individual integers.
5.3 Iterators are generalized pointers, and copying one does not copy the elements
std::vector<int> v{10, 20, 30};
auto it = v.begin();
auto it2 = it;
++it2;
std::cout << *it2; // 20
Iterators provide pointer-like traversal. Copying an iterator copies its position, not the underlying container or elements. Both iterators still refer to the same vector.
5.4 std::copy_if() selectively copies elements using iterators and a predicate
std::vector<int> src{1, 2, 3, 4, 5};
std::vector<int> dst;
std::copy_if(
src.begin(),
src.end(),
std::back_inserter(dst),
[](int x) { return x % 2 == 0; }
);
// dst = {2, 4}
copy_if traverses the input range [first, last), copying elements satisfying the predicate. back_inserter appends accepted elements to dst.
The algorithm accepts its iterators and predicate by value, without copying the input container.
6. std::optional, std::expected, and std::variant
Three value-based abstractions for representing optional values, success/failure results, and alternative types.
6.1 std::optional<T> stores either a value or nothing
std::optional<int> x; // Empty by default
x = 42;
x.has_value(); // true
if (x) {} // Check existence
*x; // Access value
x.value(); // Access with exception checking
x.value_or(0); // Return value or fallback
x.reset(); // Become empty again
std::optional<T> stores its T within the optional object, without requiring a separate allocation.
After reset():
*xhas undefined behavior.x.value()throwsstd::bad_optional_access.x.value_or(0)returns0.
6.2 std::expected<T, E> stores a success value or an error
std::expected<int, std::string> result = 42;
// Successful result
if (result) {
int x = *result;
int y = result.value();
}
// Failed result
result = std::unexpected(std::string{"Invalid input"});
if (!result) {
std::cout << result.error();
}
std::expected<T, E> represents either a valid T or an error E. Use .value() or *result to access success, and .error() to access failure.
Unlike optional, it preserves information explaining why an operation failed. .value() throws std::bad_expected_access<E> on failure.
6.3 std::variant<Ts...> stores exactly one of several possible types
std::variant<int, std::string> v = 42;
v.index(); // 0 (int)
std::holds_alternative<int>(v); // true
std::get<int>(v); // 42
std::get_if<int>(&v); // Pointer to int, or nullptr
v = std::string{"Hello"};
std::visit([](auto const& x) {
std::cout << x;
}, v);
std::variant holds one active alternative and tracks its type.
.index()identifies the active alternative.std::holds_alternative<T>()checks the active type.std::get<T>()accesses it or throws if the wrong alternative is active.std::get_if<T>()returns a pointer ornullptr.std::visit()invokes a callable with the active value.
Recall: optional<T> = value or nothing; expected<T,E> = success or error; variant<Ts...> = one of several types.
7. Function Objects, operator(), and std::function
7.1 Overloading operator() makes an object callable like a function
class Print {
public:
void operator()(int x) const {
std::cout << x;
}
};
Print p;
p(42); // Prints 42
p.operator()(42); // Equivalent
operator() is the function-call operator. An object implementing it is a function object, also called a functor.
7.2 Constructors create objects; operator() invokes existing objects
class Print {
public:
Print(int x) {
std::cout << "Construct: " << x;
}
void operator()(int x) const {
std::cout << "Invoke: " << x;
}
};
Print p(10); // Constructor
p(20); // operator()
Despite both using parentheses, construction and function invocation are distinct operations.
7.3 virtual void operator()(int) const = 0 defines a pure virtual callable interface
class Command {
public:
virtual ~Command() = default;
virtual void operator()(int) const = 0;
};
class PrintCommand : public Command {
public:
void operator()(int x) const override {
std::cout << x;
}
};
The base class specifies that derived concrete classes must implement a callable operation accepting an int. The function is virtual, const-qualified, and pure virtual.
7.4 std::function<void(int)> accepts objects callable with an integer
void f(std::function<void(int)> command) {
command(42);
}
f([](int x) {
std::cout << x;
});
Read std::function<void(int)> as: a callable accepting an int, whose result is treated as void.
The wrapper allows f to invoke the callable without knowing its concrete type.
7.5 std::function uses type erasure to support unrelated callable types
void printNumber(int x) {
std::cout << x;
}
std::function<void(int)> a = printNumber;
std::function<void(int)> b = [](int x) {
std::cout << x * 2;
};
a(10); // 10
b(10); // 20
Both a regular function and a lambda can be stored behind the same std::function<void(int)> interface.
Internally, std::function uses type erasure to invoke the stored callable without exposing its concrete type. No shared base class or user-defined virtual interface is required.
Final Takeaway — Value Semantics vs Reference Semantics
Value semantics: Objects behave as independent values. Copying creates a logically independent object, and ownership and lifetime are generally easier to reason about.
Reference semantics: Multiple references, pointers, or views may refer to the same underlying object. This enables sharing and polymorphism, but introduces aliasing, lifetime, and potential performance concerns.
Core principle: Prefer value semantics when appropriate. Use pointers, references, and non-owning views deliberately when sharing, polymorphism, or avoiding copies is necessary.