Copying c++ lambda to Function Pointer reference - c++

I am not sure if I have defined behaviour in the following situation:
My Function pointer type:
typedef void (*DoAfter_cb_type)(void);
The Function which should assign callbacks:
void DoSomething(DoAfter_cb_type & DoAfter_cb)
{
//...
DoAfter_cb = [](){
//...
};
}
Caller:
DoAfter_cb_type DoAfter_cb = nullptr;
DoSomething(DoAfter_cb);
// Here is something that has to be done after DoSomething but before DoAfter_cb.
if( DoAfter_cb != nullptr){
DoAfter_cb();
}
As I learned here lambdas can be implicitly converted to function pointers.
However thoose are still pointers and I fear that something important for calling the lambda is stored on stack and would be out of scope if I just return the function pointer
I have to use function pointers because i do not have access to std::function in my environment.
With std::function I would expect the lambda object to be stored in the reference variable and I would not have any problems.
Is the behaviour the same as If I would just define an ordinary function or do I have any side effects here?

Is the behaviour the same as If I would just define an ordinary function or do I have any side effects here?
Yes, it's the same. A captureless lambda is convertible to a regular function pointer because, to quote the C++ standard ([expr.prim.lambda.closure]/6, emphasis mine):
The closure type for a non-generic lambda-expression with no
lambda-capture has a conversion function to pointer to function with
C++ language linkage having the same parameter and return types as the
closure type's function call operator. The conversion is to “pointer
to noexcept function” if the function call operator has a non-throwing
exception specification. The value returned by this conversion
function is the address of a function F that, when invoked, has the
same effect as invoking the closure type's function call operator.
So while the lambda goes out of scope, that pointer is backed by a proper function, just as if you had written it yourself at file scope. Functions "live" throughout the entire execution of the program, so the pointer will be valid, always.

Related

Does an implicit conversion from function pointer to function exist?

I am primarily making this post to clarify some confusing/misleading information about function pointers that I stumbled upon on Stackoverflow.
Let's begin with an example:
#include <iostream>
void func ()
{
std::cout<<"func here"<<'\n';
}
int main()
{
void (*fp)()=func;
void (&fref)()=func;
func();//call through function
(&func)();//call through function pointer
(*fp)();//call through function
fp();//call through function pointer
fref();//call through function
(&fref)();//call through function pointer
}
This prints:
func here
func here
func here
func here
func here
func here
As can be seen a function can be used in place of a function pointer most of the time thanks to function to function pointer decay cppreference.
An lvalue of function type T can be implicitly converted to a prvalue pointer to that function. This does not apply to non-static member functions because lvalues that refer to non-static member functions do not exist.
But apart from that it looks a function pointer can also be used in place of a function as I can use it to call a function without explicitly derefencing.
Furthermore this Stackoverflow answer
Note also that you do not need to use the unary * to make the call via the function pointer; both (*p1_foo)(); and (p1_foo)(); have the same result, again because of the function-to-function-pointer conversion.
and this Stackoverflow answer
There's a dual convenience as well: a function pointer in call position is automatically converted to a function value, so you don't have to write * to call through a function pointer.
Make it seem like there exists an implicit function pointer to function conversion.
No
An implicit conversion from function pointer to function doesn't exist.
As of ISO International Standard ISO/IEC 14882:2020(E) – Programming Language C++ there are no mentions of such a conversion.
But apart from that it looks a function pointer can also be used in place of a function as I can use it to call a function without explicitly derefencing.
This is probably why some SO answers (and even some less known C++ books!) come to the incorrect conclusion that a function pointer is essentially the same as a function and use the function to function pointer decay as evidence. However this implicit conversion only works in one way! Meaning that the quoted section of the first SO answer is incorrect.
Why does the function call succeed anyway?
The reason as to why we can call a function using a function pointer without explicit derefernce actually lies in the way the built in function call operator "()" works cppreference:
The expression that names the function can be
a) lvalue expression that refers to a function
b) pointer to function
c) explicit class member access expression that selects a member function
d) implicit class member access expression, e.g. member function name used within another member function.
Aha! So the function call operator can directly take a function pointer as expression. There is no implicit conversion. If you read the quote from the second SO answer it explicitly mentions that the function pointer needs to be in call position that is called using the function call operator.
This also means that in all contexts outside of a function call a function pointer does need to be dereferenced where a function is expected such as when initializing a function reference:
void func ()
{
std::cout<<"func here"<<'\n';
}
int main()
{
void (*fp)()=func;//OK (implicit function to function pointer decay)
void (&&fref1)()=&func;//error: invalid initialization of reference of type 'void (&&)()' from expression of type 'void (*)()'
void (&fref2)()=*fp;//OK
void (&fref3)()=fp;// error: invalid initialization of reference of type 'void (&)()' from expression of type 'void (*)()'
}

Operator Functions Calling Mechanism

Is the calling of an operator function similar to a normal function call?
When a function call is encountered, its local variables, parameters, and the return address is loaded on to the call stack. Does this happen when we use an operator? If it happens, then the operator function should be removed from the stack after the execution is finished, right?
Well, some part of me says that it doesn't happen that way because we're returning a reference to a local object, which will be destroyed after the execution is finished.
I just want to know the details of it.
#include <stdio.h>
class OUT
{};
OUT & operator<<(OUT & out, int x)
{
printf("%d",x);
return out;
}
int main()
{
OUT print;
print<<3<<4;
}
Yes, a use of an overloaded operator function is semantically a function call.
[over.match.oper]/2 in the C++ Standard says, emphasis mine:
If either operand [in an operator expression] has a type that is a class or an enumeration, a user-defined operator function might be declared that implements this operator or a user-defined conversion can be necessary to convert the operand to a type that is appropriate for a built-in operator. In this case, overload resolution is used to determine which operator function or built-in operator is to be invoked to implement the operator. Therefore, the operator notation is first transformed to the equivalent function-call notation as summarized in Table 12 ....
So the Standard rules about object lifetimes apply in exactly the same ways. There's also no reason a compiler's manipulation of behind-the-scenes things like a call stack would need to be different.
Your example is fine not because there's something special about operator functions, but because it doesn't return a reference to a local object. In return out;, out names the function parameter with reference type, so it refers to some other object from outside of the function scope. In this case, out refers to the variable print in main, and the lifetime of print goes to the end of main.

About lambdas, conversions to function pointers and visibility of private data members

Consider the following example:
#include <cassert>
struct S {
auto func() { return +[](S &s) { s.x++; }; }
int get() { return x; }
private:
int x{0};
};
int main() {
S s;
s.func()(s);
assert(s.get() == 1);
}
It compiles both with G++ and clang, so I'm tempted to expect that is allowed by the standard.
However, the lambda has no capture list and it cannot have it because of the + that forces the conversion to a function pointer. Therefore, I expected it was not allowed to access private data members of S.
Instead, it behaves more or less how if it was defined as a static member function.
So far, so good. If I knew it before, I would have used this trick often to avoid writing redundant code.
What I'd like to know now is where in the standard (the working draft is fine) this is defined, for I've not been able to find the section, the bullet or whatever that rules about it.
Is there any limitation for the lambda or it works exactly as if it was defined as a static member function?
For lambda expressions inside the member function, according to §8.4.5.1/2 Closure types [expr.prim.lambda.closure]:
The closure type is declared in the smallest block scope, class scope, or namespace scope that contains the corresponding lambda-expression.
That means the lambda closure type will be declared inside the member function, i.e. a local class. And according to §14/2 Member access control [class.access]:
(emphasis mine)
A member of a class can also access all the names to which the class has access. A local class of a member
function may access the same names that the member function itself may access.
That means for the lambda expression itself, it could access the private members of S, same as the member function func.
And §8.4.5.1/7 Closure types [expr.prim.lambda.closure]:
(emphasis mine)
The closure type for a non-generic lambda-expression with no lambda-capture whose constraints (if any) are satisfied has a conversion function to pointer to function with C++ language linkage having the same parameter and return types as the closure type's function call operator. ... The value returned by this conversion function is the address of a function F that, when invoked, has the same effect as invoking the closure type's function call operator.
That means when the converted function pointer gets invoked the same rule applies.
However, the lambda has no capture list and it cannot have it because of the + that forces the conversion to a function pointer.
+ does not force a conversion to a function pointer, but adds a conversion operator to pointer to function for you to use as an option. Lambda remains a lambda, with all the access privileges granted to it, i.e. it may access the same names that the member function itself may access.

compile-time conversion of lambda functors into function pointers

As we know, non-capturing lambda functors can be converted to function pointers at runtime, but how about compile time? That is, is something similar to the code below possible? Please don't suggest a workaround, like passing the lambda functor as a function parameter, I'd like to know more where/how the C++11 standard forbids this.
template <void(*fptr)()>
void f()
{
// do something
}
int main()
{
auto l([]{});
f<(void(*)())(decltype(l))>();
return 0;
}
The obligatory error with gcc-4.8:
c.cpp: In function 'int main()':
c.cpp:11:7: error: parse error in template argument list
f<(void(*)())(decltype(l))>();
^
c.cpp:11:36: error: statement cannot resolve address of overloaded function
f<(void(*)())(decltype(l))>();
^
Lambda expressions, even with an empty closure, can not be used as a pointer to function template argument because they are temporaries which just happen to convert to some pointer to function. The lambda expression is a temporary according to 5.1.2 [expr.prim.lambda] paragraph 2:
The evaluation of a lambda-expression results in a prvalue temporary. [...]
The conversion to a pointer to function is desribed in paragraph 6:
The closure type for a lambda-expression with no lambda-capture has a public non-virtual non-explicit const conversion function to pointer to function having the same parameter and return types as the closure type’s function call operator. The value returned by this conversion function shall be the address of a function that, when invoked, has the same effect as invoking the closure type’s function call operator.
That is, the conversion doesn't yield a constexpr and, thus, there is no hope to use the resulting pointer to function as a template argument.
As for the reasons the best I could find for now is a statement in N3597 which points towards N2895 which seem to talk about the actual problem but I couldn't locate a detailed discussion. It seems that name-mangling for the functions created by lambda expressions is one of the problems which prohibits using them in certain contexts.

Difference in type of lambda when using [] and [this]

I have a class db_interface. And defined a lambda type:
typedef void (*db_interface_lambda)();
When I create lambda in class in such way: [](){ /* do something */ }, it has good type (db_interface_lambda), but when I use [this](){ /* do something */ }, the compiler starts to shout at me.
cannot convert ‘db_interface::db_interface(std::ifstream&)::<lambda()>’ to ‘std::map<std::basic_string<char>, void (*)()>::mapped_type {aka void (*)()}’ in assignment
How to solve that problem? What is the correct type?
Because lambdas are only implicitly convertible to function pointers if and only if they do not capture anything.
§5.1.2 [expr.prim.lambda] p6
The closure type for a lambda-expression with no lambda-capture ([] is empty) has a public non-virtual non-explicit const conversion function to pointer to function having the same parameter and return types as the closure type’s function call operator.
Btw, what you typedef'd there is a function pointer, not a lambda type. Lambda expressions have a unique, unnamed, nonunion class type. You can not name them.
§5.1.2 [expr.prim.lambda] p3
The type of the lambda-expression (which is also the type of the closure object) is a unique, unnamed nonunion class type
You're trying to call something that wants a function pointer. A captureless lambda can be converted to a function pointer automatically, but once you write [this] it ceases to be captureless - you're capturing this, so it's an error.
The solution is to change the type to be a std::function, not a pointer to a function. std::function erases the type of the "functor" it "wraps" so you can still pass a function pointer as well as a lamba with a capture.
Lambdas that do not capture anything are essentially free functions, and thus they are convertible to ordinary function pointers.
Lambdas that do capture are essentially full classes, and they cannot simply be converted to a free-function pointer. (A capturing lambda is really essentially the same predicate functor class that you would have written in C++ before we had lambdas.)
Either version of lambda is convertible to std::function<void()>, which is what the mapped type of your map should be.