Are two function pointers to the same function always equal?

北城余情 提交于 2020-01-01 07:28:05

问题


Does the C++ standard guarantee that two pointers to a function always compare equal? I understand that this will normally be true for non-inline functions. But if there is an inline function and a pointer to the function is created in two separate compilation units, will the linker merge the two instantiations, or is it allowed to emit duplicate functions?

If the answer to the above is "they are equal": Does this still hold if there is a common header with an inline function, and both the main program and a dynamically loaded plugin (shared object/DLL) create a pointer to the function?


回答1:


Section §5.10/1 of the C++11 standard says:

Two pointers of the same type compare equal if and only if they are both null, both point to the same function, or both represent the same address

Two copies of the same inline function are still the same function. From an implementation point-of-view, the compiler will generate a copy of the function in each translation unit but the linker will then throw one of the copies away so only one is remaining.

By taking the address of a function you prevent it from being inlined (different from inline, which is more about avoiding violation of the One Definition Rule).

DLLs are outside the scope of the standard but only one copy of the function will remain in the binary image so getting the function address (e.g. GetProcAddress) from the DLL will get the same function pointer as code inside the DLL.




回答2:


Does the C++ standard guarantee that two pointers to a function always compare equal?

Yes, two pointers that point to the same function compare equal.

Does this still hold if there is a common header with an inline function, and both the main program and a dynamically loaded plugin (shared object/DLL) create a pointer to the function?

Yes, per 7.1.2.p4

An inline function with external linkage shall have the same address in all translation units.



来源:https://stackoverflow.com/questions/19134124/are-two-function-pointers-to-the-same-function-always-equal

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!