Reputation: 3109
I tried to convert a lambda function into a function pointer, compile OK, but runtime crash(VC2013). This lambda function is simply to delete a pointer, like this:
typedef void(*pf)(void*);
struct M
{
~M(){ printf("dtor\n"); }
};
int main(void)
{
M *p = new M;
auto f = [](M*p){delete p; };
pf p1 = (pf)&f;
(*p1)(p);
return 0;
}
[/code]
The crash seems to happen within CRT, unable to debug by myself. Where my crash come from? Thanks a lot
Upvotes: 0
Views: 557
Reputation: 996
Deleting objects through void*
is going to get you into trouble.
void f(M*)
Here's your code that works on gcc 4.8
#include <cstdio>
class M; //forward dec
typedef void(*pf)(M*);
struct M
{
~M(){ printf("dtor\n"); }
};
int main(void)
{
M *p = new M;
auto f = [](M*p){delete p; };
pf p1 = f;
(*p1)(p);
return 0;
}
Upvotes: 0
Reputation: 8785
There are several problems:
void(*)(M*)
. pf
is void(*)(void*)
. They are not compatible! Either make lambda take void*
or change fp
to take M*
argument.Following code will work:
#include <cstdio>
struct M
{
~M(){ printf("dtor\n"); }
};
typedef void(*pf)(M*);
int main(void)
{
M *p = new M;
auto f = [](M*p){delete p; };
pf p1 = f;
(*p1)(p);
return 0;
}
Upvotes: 3