强制转换和调用函数的参数计数是否指定行为?
Is Casting and Calling a Function's Parameter Count Specified Behaviour?
这个问题具体涉及reinterpret_cast和后续使用nullptr作为第三个参数的函数调用。这是指定的行为吗?
我使用 malloc/free 是因为使用 delete
删除 void 指针是未指定的行为。无论;这个问题也应该考虑非空指针(作为参数)。
#include <cstdlib>
#include <iostream>
void *add2Ints(void *a, void *b)
{
void *res = malloc(sizeof(int));
*((int *) res) = *((int *) a) + *((int *) b);
return res;
}
int main(int argc, char *argv[])
{
void *x = malloc(sizeof(int));
void *y = malloc(sizeof(int));
*((int *) x) = 31;
*((int *) y) = 16;
void *(*add2Ints_p)(void*, void*, void*) = reinterpret_cast<void *(*)(void*, void*, void*)>(add2Ints);
void *z = add2Ints_p(x,y,nullptr);
std::cout << *((int *) z);
free(x);
free(y);
free(z);
}
使用reinterpret_cast
投射的指针的唯一合法做法是将其转换回其原始类型。
所以,在这里我们肯定在 UB 土地上(如果调用约定要求被叫方清理,你肯定会在返回时粉碎堆栈或崩溃)。
相关文章:
- 是否有C++编译器选项允许激进地删除所有函数调用,并将参数传递给具有空体的函数
- 是否可以对零模板参数进行模板专门化
- 函数作为模板参数,是否对返回类型强制约束
- visual是否可以在c++中创建一个接收无限数量相同类型(或至少相当数量)参数的函数
- 函数是否可以访问传递给main()的参数
- 在C++中,使用带有 std::optional 参数的函数<T>来表示可选参数是否有意义?
- 如何检查给定的参数是否为 cv::noArray()?
- 表达式 SFINAE:如何根据类型是否包含具有一个或多个参数的函数来选择模板版本
- 如果返回 -1,时间() 的参数是否被修改?
- 用于检查值是否为其任何参数的帮助程序函数
- 将类型声明为类型模板参数的模板参数的一部分是否合法?
- 模板化检查是否存在带有参数列表的类成员函数?
- 我如何知道作为参数的size_t在函数中是否有效?
- 是否可以在C++中有一个"generic"模板参数,该参数可以是非类型模板参数或类型?
- 是否可以就地构造一个固定大小的数组作为函数参数?
- C++方法是否可以根据传递给构造函数的参数具有不同的返回类型?
- 是否可以在运行时强制转换模板参数?
- 是否可以在不填充自己的参数的情况下将模板函数作为参数传递?
- 编译器是否强制根据模板参数计算表达式?
- C++中大多数/所有 setter 函数的参数是否应该写为常量引用?