DevAcademia lesson/C++ Functions
Passing Structures
Topic progressTopic 77 of 109 - 71% complete
~9 min lesson20 learning blocks4 code examples1 checks/interactions
Lesson outline
Design Guidelines
When designing structures for parameter passing, consider efficiency and maintainability:
- Prefer pass-by-value for small, trivially copyable structs (roughly a few machine words). This threshold is ABI- and platform-dependent—measure if performance matters.
- For larger or non-trivially copyable structs, pass by
const&for read-only access, or use pass-by-value-then-move when the function intends to consume/retain a copy. - Apply the Rule of Three/Five/Zero: either rely on generated special members (Rule of Zero), or explicitly define copy/move/dtor as needed (Three/Five).
- Consider logical immutability (e.g.,
constdata members or non-mutating interfaces) for safer, more predictable behavior.
Passing Strategies (Examples)
Pick parameter style based on how the callee uses the data:
Structured Bindings
C++17 structured bindings let you decompose aggregates, tuples, and array-like types into individual variables.
Designated Initializers (C++20)
C++20 designated initializers make aggregate initialization clearer. Designators must appear in the member declaration order and cannot be reordered.
Avoiding Copies with Moves
If a function takes ownership or needs its own copy, pass the struct by value and move from the argument internally. Callers can pass rvalues or std::move lvalues to avoid extra copies.
Pitfalls & Notes
- Passing derived objects by value slices them to the base subobject—use references/pointers for polymorphism.
- Large structs with owning members (e.g., vectors, strings) are cheap to move but potentially expensive to copy—choose parameter style accordingly.
- Prefer
std::span/views over copying containers when you only need to read elements.
Was this topic clear?