Skip to content

Value Semantics

In value semantics, data is passed around as values. Values are copied when passed into functions.

Prefer value semantics over reference semantics, if there is no specific reason to use reference semantics. It makes things simpler by avoiding the complexity and common pitfalls of reference semantics, such as nullptr, dangling pointers, lifetime dependencies, ownership semantics, etc.[^1]

STL promotes value semantics:

  • Containers are values

  • Copy implies deep copy

  • const means const

  • Algorithms take arguments by value

  • Prefer std-optional over std-unique_ptr for optional values When you need to represent optionality/nullability (“might have a value”), prefer std::optional over std::unique_ptr for simpler value semantics.

Back to Basics: Cpp Value Semantics - Klaus Iglberger - CppCon 2022