2007年8月27日星期一

Why am I having trouble taking the address of a C++ function?

[33.4] Why am I having trouble taking the address of a C++ function?

Short answer: if you're trying to store it into (or pass it as) a pointer-to-function, then that's the problem ― this is a corollary to the previous FAQ.

Long answer: In C++, member functions have an implicit parameter which points to the object (the this pointer inside the member function). Normal C functions can be thought of as having a different calling convention from member functions, so the types of their pointers (pointer-to-member-function vs. pointer-to-function) are different and incompatible. C++ introduces a new type of pointer, called a pointer-to-member, which can be invoked only by providing an object.

NOTE: do not attempt to "cast" a pointer-to-member-function into a pointer-to-function; the result is undefined and probably disastrous. E.g., a pointer-to-member-function is not required to contain the machine address of the appropriate function. As was said in the last example, if you have a pointer to a regular C function, use either a top-level (non-member) function, or a static (class) member function.

没有评论: