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

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

This is a from www.ModernesCpp.com.

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

 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 use 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 ( )
  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, it will skip the remaining rules F.23 to 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 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 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 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 for move semantic and for perfect forwarding.

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

In standard C++ you can declare main in two ways. 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 , char** ).

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 in consistent 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 often is: 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, your 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, most of the times you want to capture your variables by reference. For efficiency that means according to the rule F.16 if for your variable p holds: (p) > 4 * (int).

Because you use your lambda function locally, you will not have a lifetime issue of 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, does not exist anymore.
  2. The thread t may outlive the lifetime of the main thread. Hence, std:: 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 organise your types. The next post will be about the rules for classes and class hierarchies.

要查看或添加评论,请登录

Rainer Grimm的更多文章

社区洞察

其他会员也浏览了