Passing lambda declared using auto-keyword by non-const reference as argument to std::function parameter type

后端 未结 1 733
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-04 20:26

Consider the following code:

#include 
#include 

// passing function object by value
void foo(std::function

        
相关标签:
1条回答
  • 2021-01-04 21:07

    In your fizz(g1) case, g1 is already a std::function. Therefore, there is no need for an implicit conversion. So fizz's parameter is a non-const reference to g1.

    In fizz(g2), g2 is not a std::function. Therefore, the compiler must perform an implicit conversion. And the implicit conversion returns a temporary.

    Temporary objects cannot be bound to non-const references; they can only bind to const references or values. Hence the compiler error.

    What does const in the function parameter type mean here?

    You can only call const members of the object, you can not implicitly convert it to non-const, and you cannot perform non-const operations on its members.

    You know, just like any other use of const.

    Generally speaking, when a function takes a parameter by non-const reference, it is saying something very special about what it intends to do with that parameter. Namely, that you are handing it an object, and it is going to do non-const things with it (ie: modifying that object). That's why temporaries don't bind to non-const references; it's likely to be a mistake by the user, since the temporary may not update the original object you passed.

    Unless fizz is actually going to modify the object, you should pass it either by value or by const&.

    0 讨论(0)
提交回复
热议问题