Today, I conclude my treatise about the rules for functions in the C++ core guidelines. The last post was about the syntax of function parameters and return values. This post, with its roughly 15 rules, is about their semantics.
Before I dive into the details, here is an overview of the semantic rules for parameters, the semantic rules of return values, and a few further rules for functions.

Parameter passing semantic rules:
Value return semantic rules:
Other function rules:
Parameter passing semantic rules:
I can make this subsection relatively short. Most of the rules are already explained in the post to the Guideline Support Library. So if you are curious, read the cited post. I only want to say a few words to the first rule F.22.
What does using T* mean to designate a single object? The rule answers this question. Pointers can be used for many purposes. They can stand for a
- single object that this function must not delete
- object allocated on the heap that this function must delete
- Nullzeiger (nullptr)
- C-style string
- C-array
- location in an array
Because of these possibilities, you should use pointers only for single objects (1).
As I mentioned, it will skip the remaining rules F.23 and F.27, regarding function parameters.
Modernes C++ Mentoring
Be part of my mentoring programs:
Do you want to stay informed about my mentoring programs: Subscribe via E-Mail.
Value return semantic rules:
To say it the other way around. You should not use a pointer to transfer ownership. This is a misuse. Here is an example:
Node* find(Node* t, const string& s) // find s in a binary tree of Nodes
{
if (t == nullptr || t->name == s) return t;
if ((auto p = find(t->left, s))) return p;
if ((auto p = find(t->right, s))) return p;
return nullptr;
}
The guidelines are pretty straightforward. You should not return something from a function not in the caller's scope. The following rule stresses this point.
This rule is obvious but sometimes not so easy to spot if there are a few indirections. The issue starts with the function f, which returns a pointer to a local object.
int* f()
{
int fx = 9;
return &fx; // BAD
}
void g(int* p) // looks innocent enough
{
int gx;
cout << "*p == " << *p << '\n';
*p = 999;
cout << "gx == " << gx << '\n';
}
void h()
{
int* p = f();
int z = *p; // read from abandoned stack frame (bad)
g(p); // pass pointer to abandoned stack frame to function (bad)
}
The C++ language guarantees that a T& always refers to an object. Therefore, the caller must not check for a nullptr because no object isn't an option. This rule does not contradict the previous rule F.43 because F.43 states that you should not return a reference to a local object.
With T&&, you are asking to return a reference to a destroyed temporary object. That is extremely bad (F.43).
If the f() call returns a copy, you will get a reference to a temporary one.
template<class F>
auto&& wrapper(F f)
{
...
return f();
}
The only exceptions to these rules are std::move for move semantic and std::forward for perfect forwarding.
In standard C++, you can declare main in two ways. void is not C++ and, therefore, limits your portability.
int main(); // C++
int main(int argc, char* argv[]); // C++
void main(); // bad, not C++
The second form is equivalent to int main(int argc, char** argv).
The main function will return 0; implicitly if your main function does not have a return statement.
The copy assignment operator should return a T&. Therefore, your type is inconsistent with the standard template library's containers and follows the principle: "do as the ints do".
There is a subtle difference between returning by T& or returning by T:
A& operator=(constA& rhs){ ... };
A operator=(constA& rhs){ ... };
In the second case, a chain of operations such as A a = b = c; may result in two additional calls of the copy constructor and of the destructor.
Other function rules:
In C++11, we have callables such as functions, function objects, and lambda functions. The question is often: When should you use a function or a lambda function? Here are two simple rules
- If your callable has to capture local variables or is declared in a local scope, you have to use a lambda function.
- If your callable should support overloading, use a function.
If you need to invoke a function with a different number of arguments, prefer default arguments over overloading. Therefore, you follow the DRY principle (don't repeat yourself).
void print(const string& s, format f = {});
versus
void print(const string& s); // use default format
void print(const string& s, format f);
For performance and correctness reasons, you usually want to capture your variables by reference. For efficiency, that means according to rule F.16, if your variable p holds: sizeof(p) > 4 * sizeof(int).
Because you use your lambda function locally, you will not have a lifetime issue with your captured variable message.
std::for_each(begin(sockets), end(sockets), [&message](auto& socket)
{
socket.send(message);
});
You have to be very careful if you detach a thread. The following code snippet has two race conditions.
std::string s{"undefined behaviour"};
std::thread t([&]{std::cout << s << std::endl;});
t.detach();
- The thread t may outlive the lifetime of its creator. Hence, std::string does not exist anymore.
- The thread t may outlive the lifetime of the main thread. Hence, std::cout does not exist anymore.
If it seems that you use default capture by [=], you capture all data members by reference.
class My_class {
int x = 0;
void f() {
auto lambda = [=]{ std::cout << x; }; // bad
x = 42;
lambda(); // 42
x = 43;
lambda(); // 43
}
};
The lambda function captures x by reference.
If you want to pass an arbitrary number of arguments to a function, use variadic templates. In contrast to va_args, the compiler will automatically deduce the correct type. With C++17, we can automatically apply an operator to the arguments.
template<class ...Args>
auto sum(Args... args) { // GOOD, and much more flexible
return (... + args); // note: C++17 "fold expression"
}
sum(3, 2); // ok: 5
sum(3.14159, 2.71828); // ok: ~5.85987
If that looks strange, read my post about fold expressions.
What's next?
Classes are user-defined types. They allow you to encapsulate state and operations. Thanks to class hierarchies, you can organize your types. The next post will be about the rules for classes and class hierarchies.
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, Animus24, 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, and Rob North.
Thanks, in particular, to Jon Hess, Lakshman, Christian Wittenhorst, Sherhy Pyton, Dendi Suhubdy, Sudhakar Belagurusamy, Richard Sargeant, Rusty Fleming, John Nebel, Mipko, Alicja Kaminska, and Slavko Radman.
My special thanks to Embarcadero 
My special thanks to PVS-Studio 
My special thanks to Tipi.build 
My special thanks to Take Up Code 
Seminars
I'm happy to give online seminars or face-to-face seminars worldwide. Please call me if you have any questions.
Bookable (Online)
German
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++
New
- Clean Code with Modern C++
- C++20
Contact Me
- Phone: +49 7472 917441
- Mobil:: +49 176 5506 5086
- Mail: This email address is being protected from spambots. You need JavaScript enabled to view it.
- German Seminar Page: www.ModernesCpp.de
- Mentoring Page: www.ModernesCpp.org
Modernes C++,

Comments
found most people will go along with your views on this website.
RSS feed for comments to this post