One-liner for RAII on non pointer?

前端 未结 6 1774
小蘑菇
小蘑菇 2020-12-24 08:31

Related topic

std::unique_ptr, deleters and the Win32 API

To use a Win32 Handle as a RAII, I can use the following line

std:         


        
6条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-24 09:26

    I often use this in C++11:

     #include 
    
     namespace{
        template
        struct RAII_Helper{
            template
            RAII_Helper(InitFunction &&init, F &&exit) : f_(std::forward(exit)), canceled(false){
                init();
            }
            RAII_Helper(F &&f) : f_(f), canceled(false){
            }
            ~RAII_Helper(){
                if (!canceled)
                    f_();
            }
            void cancel(){
                canceled = true;
            }
        private:
            F f_;
            bool canceled;
        };
     }
     template
     RAII_Helper RAII_do(F &&f){
        return RAII_Helper(std::forward(f));
     }
    
     template
     RAII_Helper RAII_do(Init &&init, Exit &&exit){
        return RAII_Helper(std::forward(init), std::forward(exit));
     }
    

    usage:

    FILE *f = fopen("file", "r");
    if (!f)
        return "error";
    auto filecloser = RAII_do([=]{fclose(f);});
    
    //also makes for good init / exit objects
    static auto initExit = RAII_do([]{initializeLibrary();}, []{exitLibrary();});
    

    I like it because it works for arbitrary code, not just pointers or handles. Also the cancel function could be omitted if never used.

提交回复
热议问题