這或多或少澄清 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