Pointer-to-function Vs Pointer-to-member-function

There’s a series of C++ FAQ: http://www.parashift.com/c++-faq/pointers-to-members.html. And one of it addresses some technical details:

Pointers to member functions and pointers to data are not necessarily represented in the same way. A pointer to a member function might be a data structure rather than a single pointer. Think about it: if it’s pointing at a virtual function, it might not actually be pointing at a statically resolvable pile of code, so it might not even be a normal address – it might be a different data structure of some sort.

Let’s write some demo code:

Output on WinXP/VS2005:

Output on Ubuntu12.04/gcc4.6:

Both are run on 32bit systems. Sizes of pointer-to-member-function are not confirmed to be equal to sizeof(void *). And you are not allowed to convert a pointer-to-member-function to void * or a plain pointer-to-function type. Only equality comparisons(=, !=) are supported. Thus, it can be used to implement the “Safe Bool Idiom” here: http://www.artima.com/cppsource/safebool.html.

Perhaps the best-known use of this technique comes from the C++ Standard the conversion that allows the state of iostreams to be queried uses it.

But at least in gcc/libstdc++, its implementation uses bool and void * conversion operations. In basic_ios class:

This allows std::cout to even be deleted. Hmmm…Just write down some details here.

Leave a Reply

Your email address will not be published. Required fields are marked *