• 【C++】C++实现类似Golang的defer功能


    背景

    在Golang代码中,使用的比较多的defer是延时语句,按照倒序执行。

    Go代码的简单的demo

    func DemoFunc() {
        fmt.Println("Demo Func...")
    }
    
    func Main() {
        defer DemoFunc()
        fmt.Println("Main call.")
    }

    打印

    Main call.

    Demo Func.

    C++的实现方式

    #pragma once
    #include <functional>
    
    struct ExitCaller {
        ~ExitCaller() { functor_(); }
        ExitCaller(std::function<void()>&& functor)
            : functor_(std::move(functor)) {}
    private:
        std::function<void()> functor_;
    };

    调用方式

    // This is a example.
    // void funcX() {
    //     int fd = open(fn, O_RDONLY);
    //     if (fd < 0) {
    //     }
    //     ExitCaller ec1([=]{ close(fd); });
    //     ....
    // }

    说明

    ExitCaller在funcX中是局部变量,因此退出时,会自动调用ExitCaller的析构函数,调用对应的代码,实现业务代码的倒序执行。

    例子代码

    #include "exitcaller.hpp"
    int main(int argc, char** argv ) {
        ExitCaller ec1([=] {
            std::cout << "Main Exit 1" << std::endl;
        });
        ExitCaller ec2([=] {
            std::cout << "Main Exit 2" << std::endl;
        });
        std::cout << "Main Call" << std::endl;
        return 0;
    }

    打印

    Main Call
    Main Exit 2
    Main Exit 1

    这种实现方式借鉴Golang的defer思路实现。

    Done.

    祝玩的愉快~

  • 相关阅读:
    Finance_Time-Series-Analysis-with-app-in-R
    Linear_algebra_06_二次型
    Linear_algebra_05_相似对角形
    病理学
    S&p_14_参数的假设检验
    S&p_13_参数区间估计
    Finance_Analysis-of-Financial-Time-Series
    817. Linked List Components
    811. Subdomain Visit Count
    807. Max Increase to Keep City Skyline
  • 原文地址:https://www.cnblogs.com/voipman/p/15251614.html
Copyright © 2020-2023  润新知