Rvalue reference link to lvalue for std :: function types

Why is there no compilation error (@)in the lower code? I thought it was lamban lvalue, so it would not be bound to an rvalue reference.

using FunctionType = std::function<void()>;
using IntType = int;
struct Foo {
    void bar(FunctionType&&) {}
    void baz(IntType&&) {}
};

Foo foo;
foo.bar([]() {}); //OK
auto lamb = []() {};
foo.bar(lamb); //(@) No compilation error?!
foo.baz(5); //OK
int i = 5;
foo.baz(i); //Error
+4
source share
1 answer

Since it lambis a lambda, not a std::function, a temporary std::functionshould be created and passed in bar(). Temporary reference to rvalue link.

Your code is equivalent to this:

auto lamb = [](){};
foo.bar(FunctionType(lamb));

If you do this, you will get a compilation error:

FunctionType func = [](){};
foo.bar(func);
+8
source

Source: https://habr.com/ru/post/1665162/


All Articles