• 记一个SGI空间配置器的设置OOM处理函数的用法


    示例如下:

    #include 
    using namespace std;
    
    // 定义一个函数指针类型__malooc_aloc_oom_handler别名,实际为void(*)();
    // 此处可以注释掉,因为直接使用void(*)()也是可以的
    using __malooc_aloc_oom_handler = void(*)();
    
    // 待测试传入的函数
    void fun(){
        cout <<  " name " << endl;
    }
    
    // 设置oom处理函数的函数句柄
    // 函数名为set_malloc_handler
    // 参数为void (*f)()函数指针
    // 返回值为void (*)()函数指针
    void (*set_malloc_handler(void (*f)()))(){
        // __malooc_aloc_oom_handler fh = f;
        void(*fh)() = f; // 可以运行!
        (*fh)();
        return fh;
    }
    
    int main(){
        set_malloc_handler(fun);
        return 0;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27

    那么如果将它分装成类呢?
    如下

    #include 
    using namespace std;
    void fun(){
        cout <<  " name " << endl;
    }
    
    class oom_handler{
        private:
            void (*ph)();
        public:
            oom_handler():ph(nullptr){}
            void (*set_malloc_handler(void (*f)()))(){
                void (*old)() = ph;
                ph = f;
                return old;
            }
    
            void call(){
                if(ph){
                    (*ph)();
                }else{
                    cout << "ph is nullptr!\n";
                }
            }
    };
    
    int main(){
        oom_handler oh;
        oh.set_malloc_handler(fun);
        oh.call();
        oh.set_malloc_handler(nullptr);
        oh.call();
        return 0;
    }
    /*
     name 
    ph is nullptr!
    */
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38

    当然也可以封装成静态的。
    如果用现代c++进行改进的话,set_malloc_handler可以进行改进,如下写法auto set_malloc_handler(functional fun);这样更能看出来函数的声明。原生的实话说不太好看明白。

  • 相关阅读:
    【数学相关知识-概率和矩阵】
    解放你的双手----WIN7设置自动化任务
    数学建模 Matlab Simulink
    Vue3+elementplus搭建通用管理系统实例八:通用表格实现中
    安装RPM包或源码包
    WebSocket的核心事件
    `算法知识` 哈希
    关于vray 5.2的使用(自研笔记)
    const关键字
    HTML小游戏2—— 2048网页版(附完整源码)
  • 原文地址:https://blog.csdn.net/A315776/article/details/126586246