cogs

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

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.

cogs

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.

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

 

Rainer D 6 P2 500x500Modernes C++ Mentoring

  • "Fundamentals for C++ Professionals" (open)
  • "Design Patterns and Architectural Patterns with C++" (open)
  • "C++20: Get the Details" (open)
  • "Concurrency with Modern C++" (open)
  • "Generic Programming (Templates) with C++": October 2024
  • "Embedded Programming with Modern C++": October 2024
  • "Clean Code: Best Practices for Modern C++": March 2025
  • Do you want to stay informed: Subscribe.

     

    1. single object that this function must not delete
    2. object allocated on the heap that this function must delete
    3. Nullzeiger (nullptr)
    4. C-style string
    5. C-array
    6. 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.

    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 pretty straightforward. You should not return something from a function not in the caller’s scope. The following rule stresses this point.

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

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

     

    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& 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.

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

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

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

     

    versus

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

     

    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;});
    t.detach();
    

     

    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 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 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, Jozo Leko, John Breland, Venkat Nandam, Jose Francisco, Douglas Tinkham, Kuchlong Kuchlong, Robert Blanch, Truels Wissneth, 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, Stephen Kelley, Kyle Dean, Tusar Palauri, 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, Marco Parri Empoli, Philipp Lenk, Charles-Jianye Chen, Keith Jeffery,and Matt Godbolt.

    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
    My special thanks to SHAVEDYAKS

    Modernes C++ GmbH

    Modernes C++ Mentoring (English)

    Do you want to stay informed about my mentoring programs? Subscribe Here

    Rainer Grimm
    Yalovastraße 20
    72108 Rottenburg

    Mobil: +49 176 5506 5086
    Mail: schulung@ModernesCpp.de
    Mentoring: www.ModernesCpp.org

    Modernes C++ Mentoring,

     

     

    0 replies

    Leave a Reply

    Want to join the discussion?
    Feel free to contribute!

    Leave a Reply

    Your email address will not be published. Required fields are marked *