考虑以下代码:
#include <iostream>
typedef int (*test_func_t) (int, int, int);
int print_integer (int a)
{
std::cout << "num: " << a << "\n";
return a;
}
int main (int argc, char * argv[])
{
test_func_t func = (test_func_t) &print_integer;
std::cout << "calling with 3 parameters func(5,7,9)\n";
func(5,7,9);
return 0;
}
如您所见,类型 (test_func_t) 被定义为具有 3 个 int 参数的函数。函数指针 (func) 被分配了一个指向“print_integer”的指针,它只接收 1 个参数,然后使用 3 个参数(5、7、9)调用函数指针。
此代码有效并产生“num: 5”输出。
gdb disas 输出(Intel 语法)
disas main
...
0x080486cb <+9>: mov DWORD PTR [esp+0x1c],0x804867d
...
0x080486e0 <+37>: mov DWORD PTR [esp+0x8],0x9
0x080486e8 <+45>: mov DWORD PTR [esp+0x4],0x7
0x080486f0 <+53>: mov DWORD PTR [esp],0x5
0x080486f7 <+60>: mov eax,DWORD PTR [esp+0x1c]
0x080486fb <+64>: call eax
disas print_integer
...
0x08048683 <+6>: mov DWORD PTR [esp+0x4],0x8048830
0x0804868b <+14>: mov DWORD PTR [esp],0x8049ae0
0x08048692 <+21>: call 0x8048530 <std::basic_ostream<char, std::char_traits<char> >& std::operator<< <std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&, char const*)@plt>
0x08048697 <+26>: mov edx,DWORD PTR [ebp+0x8]
0x0804869a <+29>: mov DWORD PTR [esp+0x4],edx
0x0804869e <+33>: mov DWORD PTR [esp],eax
0x080486a1 <+36>: call 0x80484d0 <std::ostream::operator<<(int)@plt>
如您所见,其余参数([ebp+0x12] 和 [ebp+0x16])根本没有使用。
我的问题:
- 这似乎适用于具有 __cdecl 调用约定的 Linux x86。它在其他架构和调用约定上是否也安全?
- 是否有任何 C/C++ 标准允许/定义从需要较少参数的函数中分配函数指针的结果?
这种用法的例子:node.js 的 NODE_MODULE注册一个函数,其 type有 3 个参数 [exports、module、priv]。是called with those 3但正式示例显示使用 1 注册函数或 2参数。
最佳答案
引用自 C++11 标准 expr.reinterpret.cast 6:
A function pointer can be explicitly converted to a function pointer of a different type. The effect of calling a function through a pointer to a function type (8.3.5) that is not the same as the type used in the definition of the function is undefined.
所以,我想说它一般不安全。这是未定义的行为。也就是说,我不知道其他 C++ 实现在这种情况下的表现如何。
关于c++ - 调用一个函数指针,其分配的函数的参数少于指针类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31479552/