The choice of passing parameters by value, reference, const reference, or forwarding reference depends on your specific use case:
Pass by value when:
Pass by reference (&
)Â when:
Pass by const reference (const &
)Â when:
Pass by forwarding reference (&&
)Â when:
For example:
template <typename... Types>
void LogByValue(Types... Args) {
// Each arg copied into the function
(std::cout << ... << Args) << '\n';
}
template <typename... Types>
void LogByReference(Types&... Args) {
// Each arg passed by reference
(std::cout << ... << Args) << '\n';
Args...; // Potential to modify arguments
}
template <typename... Types>
void LogByConstRef(const Types&... Args) {
// Each arg passed by const reference
(std::cout << ... << Args) << '\n';
// Args...; // Can't modify arguments
}
template <typename... Types>
void LogAndForward(Types&&... Args) {
(std::cout << ... << Args) << '\n';
SomeOtherFunction(std::forward<Types>(Args)...);
}
In general, prefer passing by value for small types and const reference for large types. Use non-const references when you need to modify arguments, and forwarding references when you need to forward arguments while preserving their original value category.
Answers to questions are automatically generated and may not have been reviewed.
An introduction to variadic functions, which allow us to pass a variable quantity of arguments