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

沒接觸過函數指針的人看到這段代碼可能會很頭疼,不知道這個函數表達什麼意思。spa

其實咱們應該由內向外讀這段代碼的首部:指針

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的尾置返回類型表達式函數首部能夠寫成這樣:perl

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

其中參數類型和返回類型都是void (*)()static

其實,咱們爲了閱讀方便,能夠改變一下寫法,在C++中,咱們能夠這樣寫:word

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表達式:co

using PF = void (*)();
相關文章
相關標籤/搜索