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);
}

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

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

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

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

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

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

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

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

其实,咱们为了阅读方便,能够改变一下写法,在C++中,咱们能够这样写:di

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);
}

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

在C++11新标准中咱们也能够把以上typedef类型定义改为using表达式:阅读

using PF = void (*)();

 

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

相关文章
相关标签/搜索