问题由来
在阅读《STL源码剖析》的时候遇到一个函数
static void (* set_malloc_handler(void (*f)()))()
{
void (* old)() = __malloc_alloc_oom_handler;
__malloc_alloc_oom_handler = f;
return(old);
}
要弄明白这个问题,首先得知道函数指针。
函数指针
reference:《C++ primer》第五版
函数指针指向一个函数,它所指向的类型由其所指向的函数的返回类型和形参类型共同决定。比如下面这个函数
bool lengthCompare(const string &, cosnt string &);
这个函数类型是bool (const string &, const string &).现在我们声明一个函数指针,用指针替换函数名
bool (*pf)(const string &, cosnt string &);
观察这个声明:pf前面的*表示pf是一个指针,右侧形参列表表示pf是指向一个函数,左侧函数的返回值是bool类型。
使用函数指针:先让函数指针指向一个函数,然后这个指针就和函数名一样使用
pf = lengthCompare;
bool b1 = pf("hello", "goodbye");
函数指针作为形参(重要)
以下函数的第3个参数为一个函数指针
void useBigger(const string &s1, const string &s2, bool (*pf)(const string &, const string &));
当使用的时候,我们可以直接把函数作为实参传入,它便自动转为指针
useBigger(s1, s2, lengthCompare);
函数指针作为返回值(重要)
using F = int(int*, int); //F为函数类型
using PF = int(*)(int*, int); //PF为函数指针类型
PF fl(int); //f1和f2都是返回函数指针类型
F* f2(int);
我们也可这样声明f1:
int (*f1(int)) (int*, int);
由内向外读:f1有形参列表,是一个函数;前面有一个*,所以f1返回一个指针;进一步观察,指针类型本身也包含形参列表,因此指针指向函数,该函数(就是指针指向的函数)的返回类型为int.
分析static void (* set_malloc_handler(void (*f)()))()
static void (* set_malloc_handler(void (*f)()))()
{
void (* old)() = __malloc_alloc_oom_handler;
__malloc_alloc_oom_handler = f;
return(old);
}
从里往外读:set_malloc_handlers有形参列表,是一个函数;函数参数为void(f)(),很显然,这个参数是一个函数指针,参数为空,返回类型也为空;函数名前面有一个,所以返回一个指针;进一步观察这个指针类型也有参数列表,因此该指针指向一个函数,这个函数的参数为空,返回类型为void;因此:函数set_malloc_handler的参数为void()()类型,返回值也为void()()类型。