Search code examples
c++compilationpointer-to-member

C++ function pointer's address invariance


I know that function pointers` addresses do not change among various compilation units.

struct Interface
{
   void sum(int, int);
};

For instnce, &Interface::sum will yield the same value among different units (Am I wrong?).

  1. At what extent does this hold? Will the address be the same when compiled on a different machine, system?
  2. Can a function address be a reliable tool to use in a public header? For example, to use it for internal mapping or tag dispatching.

I suspect it might be different when a different compiler is used.

I ask this assuming that we have the same size for a function pointer (i.e. for x64).


Solution

  • First of all, I would like to emphasize that the fact that sum is a method is unrelated to the answer.

    Second, the address will be the same across all compilation units because it's the most efficient - otherwise, you have to duplicate sum in the executable. If it's in only once place, every caller can just call there.

    Third, the address might not be the same even if you rerun the program. It probably will, if the executable loads to the same base address, but there's no guarantee. Therefore, the address also isn't guaranteed to be the same on a different machine/system, and isn't a reliable tool to use in a header file.

    Last, a different compiler, or even using the same compiler after slightly changing the code, may place sum in a different location in your executable, so your final suspicion was correct.