C++ Core Guidelines: Semantic of Function Parameters and Return Values

Today,  I conclude my treatise about the rules to 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 to functions.


Parameter passing semantic rules:

Value return semantic rules:

Other function rules:

Parameter passing semantic rules:

I can make this subsection quite 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.

F.22: Use T* or owner<T*> to designate a single object

 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

  1. single object that must not be deleted by this function
  2. object allocated on the heap that must be deleted by this function
  3. Nullzeiger (nullptr)
  4. C-style string
  5. C-array
  6. location in an array

Because of this bunch of possibilities, you should use pointers only for single objects (1).

As I already mentioned, it will skip the remaining rules F.23 to F.27 regarding function parameters.


Rainer D 6 P2 540x540Modernes C++ Mentoring

Stay informed about my mentoring programs. Subscribe for the news.



Value return semantic rules:

F.42: Return a T* to indicate a position (only)

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 quite clear. You should not return something from a function that is not in the caller's scope. The next rule stresses this point.

F.43: Never (directly or indirectly) return a pointer or a reference to a local object

This rule is quite 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)


F.44: Return a T& when the copy is undesirable and “returning no object” isn’t an option

The C++ language guarantees that a T& refers always to an object. Therefore, the caller must not check for a nullptr because no object isn't an option. This rule is not in contradiction to the previous rule F.43 because F.43 states that you should not return a reference to a local object.

F.45: Don’t return a T&&

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.

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.

F.46: int is the return type for main()

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.

F.47: Return T& from assignment operators.

The copy assignment operator should return a T&. Therefore, your type is inconsistent with the containers of the standard template library and follow the principle: "do as the ints do".

There is a subtle difference between returning by T& or returning by T:

  1. A& operator=(constA& rhs){ ... };
  2. 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:

F.50: Use a lambda when a function won’t do (to capture local variables, or to write a local function)

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.

F.51: Where there is a choice, prefer default arguments over overloading

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 = {});



void print(const string& s);  // use default format
void print(const string& s, format f);


F.52: Prefer capturing by reference in lambdas that will be used locally, including passed to algorithms

For performance and correctness reasons, most of the time you want to capture your variables by reference. For efficiency that means according to the rule F.16 if for 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)


F.53: Avoid capturing by reference in lambdas that will be used nonlocally, including returned, stored on the heap, or passed to another thread

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;});


  1. The thread t may outlive the lifetime of its creator. Hence, std::string does not exist anymore.
  2. The thread t may outlive the lifetime of the main thread. Hence, std::cout does not exist anymore.

F.54: If you capture this, capture all variables explicitly (no default capture)

If it seems that you use default capture by [=], you actually 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.

F.55: Don’t use va_arg arguments

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 right 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


In case that looks strange to you, read my previous 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, Marko, 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, Evangelos Denaxas, 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, and Phillip Diekmann.


Thanks in particular to Jon Hess, Lakshman, Christian Wittenhorst, Sherhy Pyton, Dendi Suhubdy, Sudhakar Belagurusamy, Richard Sargeant, Rusty Fleming, Ralf Abramowitsch, John Nebel, Mipko, and Alicja Kaminska.



My special thanks to Embarcadero CBUIDER STUDIO FINAL ICONS 1024 Small


My special thanks to PVS-Studio PVC Logo



I'm happy to give online seminars or face-to-face seminars worldwide. Please call me if you have any questions.

Bookable (Online)


Standard Seminars (English/German)

Here is a compilation of my standard seminars. These seminars are only meant to give you a first orientation.


Contact Me

Modernes C++,



Tags: functions


0 #1 Leonel 2017-08-22 02:55
You have made some really good points there. I looked on the net for more information about the issue and
found most people will go along with your views on this website.


Stay Informed about my Mentoring


English Books

Course: Modern C++ Concurrency in Practice

Course: C++ Standard Library including C++14 & C++17

Course: Embedded Programming with Modern C++

Course: Generic Programming (Templates)

Course: C++ Fundamentals for Professionals

Interactive Course: The All-in-One Guide to C++20

Subscribe to the newsletter (+ pdf bundle)

Blog archive

Source Code


Today 60

Yesterday 6484

Week 6544

Month 27291

All 10948752

Currently are 201 guests and no members online

Kubik-Rubik Joomla! Extensions

Latest comments