Why can function pointers be `constexpr`?

前端 未结 4 2042
花落未央
花落未央 2021-02-03 22:31

How does the compiler know where in memory the square root will be before the program is executed? I thought the address would be different everytime the program is executed, bu

4条回答
  •  野性不改
    2021-02-03 23:09

    It's simple.

    Consider how compiler knows the address to call in this code:

    puts("hey!");
    

    Compiler has no idea of the location of puts, and it also doesn't add a runtime lookup for it (that'd be rather bad for performance, though it is actually what virtual methods of classes need to do). The possibility of having a different version of dynamic library at runtime (not to mention address space layout randomization even if it is the exact same library file) makes sure the build time toolchain linker doesn't know it either.

    So it's up to the dynamic linker to fix the address, when it starts the compiled binary program. This is called relocation.

    Exact same thing happens with your constexpr: compiler adds every place in the code using this address to the relocation table, and then dynamic linker does its job every time the program starts.

提交回复
热议问题