c++ - Casting pointer to function types -
c++ - Casting pointer to function types -
so in "the c++ programming language, 4th edition", there's paragraph don't understand conversion of pointer-to-function types. here of code sample.
using p1 = int(*)(int*); using p2 = void(*)(void); void f(p1 pf) { p2 pf2 = reinterpret_cast<p2>(pf); pf2(); // serious problem // other codes } when run crashed.
i'm not sure if right, think "likely serious problem" comment when pf got casted p2 in pf2, think pf2 not pointing anything? because when created function matches p2's type , point pf2 it, didn't crash , runs normally.
after code, read this:
need nastiest of casts, reinterpret_cast, conversion of pointer-to-function types. reason result of using pointer function of wrong type unpredictable , system-dependent. example, in illustration above, called function may write object pointed argument, phone call pf2() didn’t supply argument!now i'm lost starting "for example, in illustration above" part:
"may write object pointed argument" //what object exactly? "but phone call pf2() didn’t supply argument!" //"using p2 = void(*)(void);" doesn't need arguement it?i think i'm missing here. can explain this?
for example, in illustration above, called function may write object pointed argument (...)
pf pointer function this:
int foo(int* intptr) { // ... } so implemented write argument:
int foo(int* intptr) { *intptr = 42; // writing address given argument homecoming 0; } (...) phone call pf2() didn’t supply argument!
when phone call foo through cast type p2, called without arguments, unclear intptr be:
p2 pf2 = reinterpret_cast<p2>(pf); pf2(); // no argument given here, although pf2 foo() , expects one! writing corrupt something.
moreover, compilers implement calls functions homecoming reserving space homecoming value first, filled function call. when phone call p1 using signature of p2, phone call p2 won't reserve space (as homecoming value void) , actual phone call write int somewhere should not, source corruption.
c++ function pointers
Comments
Post a Comment