STL函数static void (* set_malloc_handler(void (*f)()))()与函数指针解析

在C++ STL的SGI实现版本中,一级空间配置器class __malloc_alloc_template中有一个静态函数的实现如下:

static void (*set_malloc_handler(void (*f)()))() {
    void (*old)() = __malloc_alloc_oom_handler;
    __malloc_alloc_oom_handler = f;
    return (old);
}

没接触过函数指针的人看到这段代码可能会很头疼,不知道这个函数表达什么意思。

其实我们应该由内向外读这段代码的首部:

void (*set_malloc_handler(void (*f)()))()

当我们看到set_malloc_handler有函数调用运算符和参数:(void (*f)()),说明这是个函数,以一个void (*)()类型的函数指针f做为参数(即f是一个函数指针,指向的函数为空参数列表,无返回值),set_malloc_handler前面有一个*,所以这个函数应该返回一个指针,然后指针本身也有空参数列表(),因此该指针指向函数,该函数的返回值也是void,参数列表也为空。

综合起来说,就是我们定义了一个函数set_malloc_handler,它接受一个void (*)()类型的参数f,返回类型为void (*)()。

利用C++11的尾置返回类型表达式函数首部可以写成这样:

auto set_malloc_handler(void (*f)()) -> void (*)()

其中参数类型和返回类型都是void (*)()

其实,我们为了阅读方便,可以改变一下写法,在C++中,我们可以这样写:

typedef void (*PF)(); //我们定义一个函数指针类型PF代表void (*)()类型
static PF set_malloc_handler(PF f) {
    PF old = __malloc_alloc_oom_handler;
    __malloc_alloc_oom_handler = f;
    return (old);
}

这样看起来就比较通俗易懂了。

在C++11新标准中我们也可以把以上typedef类型定义改成using表达式:

using PF = void (*)();

PS:不懂函数指针的可以参考《C++ Primer(第五版)》6.7节

原文地址:https://www.cnblogs.com/Chierush/p/3745520.html