You have many choices to pass function parameters. You can pass by value or by reference. A reference can be const or non-const. You can even move or forward your parameters. Your decision should depend on if it is an in, and out, an in-out, a consume, or a forward function parameter. Curious? Read the post!
According to the guidelines, let’s discuss in, out, in-out, consume, or forward parameters.
Parameter passing expression rules:
- F.15: Prefer simple and conventional ways of passing information
- F.16: For “in” parameters, pass cheaply-copied types by value and others by reference to
- F.17: For “in-out” parameters, pass by reference to non-
- F.18: For “consume” parameters, pass by
- F.19: For “forward” parameters, pass by
- F.20: For “out” output values, prefer return values to output parameters
- F.21: To return multiple “out” values, prefer returning a tuple or struct
- F.60: Prefer
T&when “no argument” is a valid option
It seems to be a lot of stuff, but bear with me. The first rule F.15 summarises the guidelines F.16 – F.21
Here is the big picture from the C++ core guidelines. These are the standard parameter passing rules.
Based on these rules there are a few additions in green, the so-called advanced parameter passing rules.
The rationale for the rules and their variations will follow in the next rules.
This rule for in parameters is straightforward, and so is the example:
I often hear the question in my seminars: What is cheaply copyable? The guidelines are pretty concrete.
- You should not copy the parameter p if sizeof(p) > 4 * sizeof(int)
- You should not use a const reference to p if sizeof(p) < 3 * sizeof(int)
I assume these numbers are based on experience.
In-out parameters will be modified in the function, so using a non-const reference makes sense.
This is the first advanced rule to consume parameters. Use an rvalue reference if you consume the parameter and move it inside the function body. Here is an example:
There is an exception to this rule. std::unique_ptr is a move-only type that is cheap to move. Therefore, you can move it.
This is the idiom that factory methods such as std::make_unique or std::make_shared use. Both functions take a type T and arbitrary numbers of arguments args and forward them unchanged to the constructor of T. Have a look here:
This pattern is called perfect forwarding: If a function templates forward its arguments without changing its lvalue or rvalue characteristics, we call it perfect forwarding.
Here is my previous post to perfect forwarding.
To get perfect forwarding for a function template, you have to follow the three-step recipe. I skip this part because it must not be a variadic template (…) such as for std::make_unique.
- You need a template parameter: typename Args
- Take your function argument per forwarding reference: Args&& args
- Forward the function arguments: std::forward<Args>(args)
An explicit return value documents the intention of a function. Using a parameter with a reference as out output value may be misleading. This can also be an in-out value. Returning the result of a function by value also holds for the standard container that uses move semantics implicitly.
There is an exception to this rule. If you have an expensive-to-move object, you can use a reference as out parameter.
Sometimes your function returns more than one out value. In this case, you should use a std::tuple or a struct, but you should not use the parameter with a reference. This is very error-prone.
With C++17 and structured binding returning more than one value becomes quite convenient.
The function getValue returns a pair. success indicates if the query for the key was successful.
The next rule is special. For me, this rule is more of a semantic rule. But anyway.
If your parameter can never get a “no argument” such as a nullptr, you should use a T&. T& cannot be a nullptr. If nullptr is possible, use T*.
If no argument is an option, you have to check for it.
This post was about in, out, in-out, consume, and forward parameters, but there are more questions to answer. How should you deal with sequences or with ownership? I will write about it in the next post.
Thanks a lot to my Patreon Supporters: Matt Braun, Roman Postanciuc, Tobias Zindl, G Prvulovic, Reinhold Dröge, Abernitzke, Frank Grimm, Sakib, Broeserl, António Pina, Sergey Agafyin, Андрей Бурмистров, Jake, GS, Lawton Shoemake, Jozo Leko, John Breland, Venkat Nandam, Jose Francisco, Douglas Tinkham, Kuchlong Kuchlong, Robert Blanch, Truels Wissneth, Kris Kafka, Mario Luoni, Friedrich Huber, lennonli, Pramod Tikare Muralidhara, Peter Ware, Daniel Hufschläger, Alessandro Pezzato, Bob Perry, Satish Vangipuram, Andi Ireland, Richard Ohnemus, Michael Dunsky, Leo Goodstadt, John Wiederhirn, Yacob Cohen-Arazi, Florian Tischler, Robin Furness, Michael Young, Holger Detering, Bernd Mühlhaus, Matthieu Bolt, Stephen Kelley, Kyle Dean, Tusar Palauri, Dmitry Farberov, Juan Dent, George Liao, Daniel Ceperley, Jon T Hess, Stephen Totten, Wolfgang Fütterer, Matthias Grün, Phillip Diekmann, Ben Atakora, Ann Shatoff, Rob North, Bhavith C Achar, and Marco Parri Empoli.
Thanks, in particular, to Jon Hess, Lakshman, Christian Wittenhorst, Sherhy Pyton, Dendi Suhubdy, Sudhakar Belagurusamy, Richard Sargeant, Rusty Fleming, John Nebel, Mipko, Alicja Kaminska, Slavko Radman, and David Poole.
|My special thanks to Embarcadero|
|My special thanks to PVS-Studio|
|My special thanks to Tipi.build|
|My special thanks to Take Up Code|
I’m happy to give online seminars or face-to-face seminars worldwide. Please call me if you have any questions.
- Embedded Programmierung mit modernem C++ 12.12.2023 – 14.12.2023 (Präsenzschulung, Termingarantie)
Standard Seminars (English/German)
Here is a compilation of my standard seminars. These seminars are only meant to give you a first orientation.
- C++ – The Core Language
- C++ – The Standard Library
- C++ – Compact
- C++11 and C++14
- Concurrency with Modern C++
- Design Pattern and Architectural Pattern with C++
- Embedded Programming with Modern C++
- Generic Programming (Templates) with C++
- Clean Code with Modern C++
- Phone: +49 7472 917441
- Mobil:: +49 176 5506 5086
- Mail: schulung@ModernesCpp.de
- German Seminar Page: www.ModernesCpp.de
- Mentoring Page: www.ModernesCpp.org
Modernes C++ Mentoring,