是同一函数的两个函数指针总是相等吗? [英] Are two function pointers to the same function always equal?

查看:359
本文介绍了是同一函数的两个函数指针总是相等吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C ++标准保证函数的两个指针总是比较相等吗?我理解这通常适用于非内联函数。但是如果有一个内联函数和一个指向该函数的指针在两个独立的编译单元中创建,链接器会合并两个实例,还是允许它们发出重复的函数?



如果上面的答案是他们是相等的:如果有一个内联函数的公共头,并且主程序和动态加载的插件(共享对象/ DLL)创建一个指针到函数?

解决方案

C ++ 11标准的§5.10/ 1说:


相同类型的两个指针当且仅当它们是
时都比较为等于null,都指向相同的函数,或者两者都表示相同的
address


两个相同的 inline 函数副本仍然相同功能。从实现的角度来看,编译器将在每个翻译单元中生成一个函数的副本,但是链接器将抛出一个副本,所以只剩下一个副本。



通过使用函数的地址,可以防止它被内联(不同于 inline ,这是为了避免违反单一定义规则)。

DLL不在标准的范围内,但只有一个函数副本将保留在二进制映像中,因此获取函数地址(例如 GetProcAddress )从DLL中获得与DLL中的代码相同的函数指针。


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?

解决方案

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.

这篇关于是同一函数的两个函数指针总是相等吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆