C++ - 以下代码会导致未定义的行为吗?
C++ - Can the following code cause undefined behavior?
看看下面的例子:
#include <iostream>
#include <string.h>
void Func1(int x)
{
std::cout << "I'm function 1: " << x << std::endl;
}
void Func2(int x, const char* str)
{
std::cout << "I'm function 2: (this is arg1: " << x << " - args2: " << str << ")" << std::endl;
}
uintptr_t GetProcAddress(const char* _str)
{
if (strcmp(_str, "func1") == 0)
{
return reinterpret_cast<uintptr_t>(Func1);
}
else
{
return reinterpret_cast<uintptr_t>(Func2);
}
}
int main()
{
typedef void(*PROCADDR)(int, const char*);
PROCADDR ext_addr = nullptr;
ext_addr = (PROCADDR)GetProcAddress((const char*)"func1");
//call the function
ext_addr(10, "arg");
std::cin.get();
return 0;
}
我们基本上是使用 2 个参数调用 Func1,并且可以切换为使用相同的参数调用 Func2,一切都按预期进行。
当然,两个参数的地址总是被压入堆栈,即使函数本身从未使用过第二个参数。
现在我明白上面的代码永远不应该在生产代码中使用,但我的主要问题是,上面的代码会导致 UB 还是代码总是这样?
此致
xx
是的,这是未定义的行为。来自 [expr.reinterpret.cast]:
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.
看看下面的例子:
#include <iostream>
#include <string.h>
void Func1(int x)
{
std::cout << "I'm function 1: " << x << std::endl;
}
void Func2(int x, const char* str)
{
std::cout << "I'm function 2: (this is arg1: " << x << " - args2: " << str << ")" << std::endl;
}
uintptr_t GetProcAddress(const char* _str)
{
if (strcmp(_str, "func1") == 0)
{
return reinterpret_cast<uintptr_t>(Func1);
}
else
{
return reinterpret_cast<uintptr_t>(Func2);
}
}
int main()
{
typedef void(*PROCADDR)(int, const char*);
PROCADDR ext_addr = nullptr;
ext_addr = (PROCADDR)GetProcAddress((const char*)"func1");
//call the function
ext_addr(10, "arg");
std::cin.get();
return 0;
}
我们基本上是使用 2 个参数调用 Func1,并且可以切换为使用相同的参数调用 Func2,一切都按预期进行。
当然,两个参数的地址总是被压入堆栈,即使函数本身从未使用过第二个参数。
现在我明白上面的代码永远不应该在生产代码中使用,但我的主要问题是,上面的代码会导致 UB 还是代码总是这样?
此致 xx
是的,这是未定义的行为。来自 [expr.reinterpret.cast]:
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.