这或多或少澄清 Casting a function pointer to another type与示例代码的请求优化了辅助功能
struct my_struct;
void my_callback_function(struct my_struct* arg);
void do_stuff(void (*cb)(void*));
static void my_callback_helper(void* pv)
{
my_callback_function(pv);
}
int main()
{
do_stuff(&my_callback_helper);
}
回答说,“好”的编译器应该能够优化出 的my_callback_helper()
功能,但我发现没有编译器在https://gcc.godbolt.org ,做它和辅助功能被一直产生,即使它just a jump to my_callback_function()
(-O3):
my_callback_helper:
jmp my_callback_function
main:
subq $8, %rsp
movl $my_callback_helper, %edi
call do_stuff
xorl %eax, %eax
addq $8, %rsp
ret
所以我的问题是:标准中有什么能够防止编译器消除帮助者?
以我的经验,编译器倾向于在即使在编译时确定的函数指针的值内联函数指针调用做的不好。你可以试着折腾'inline'关键字。据我所知,标准中没有任何内容阻止优化。 – Lundin