Call a function before function exits

前端 未结 5 799
抹茶落季
抹茶落季 2021-01-28 21:49

I will begin with an example. Suppose I need to guard a code with a function inside a mutex. There are two ways of implementing this.

#include 
#         


        
5条回答
  •  感情败类
    2021-01-28 22:29

    You may write your own geneirc RAII class, something like:

    class Finally
    {
    public:
        explicit Finally(std::function f) : mF(f) {}
        ~Finally() noexcept() {
            try
            {
                mF();
            } catch (...) {
                // Handle error.
            } 
        }
    
        Finally(const Finally&) = delete;
        Finally(Finally&&) = delete;
    
        Finally& operator=(const Finally&) = delete;
        Finally& operator=(Finally&&) = delete;
    
    private:
        std::function mF;
    };
    

    Usage:

    {
        pthread_mutex_lock(&myMutex);
        Finally finally([&](){ pthread_mutex_unlock(&myMutex); });
    
        //..
    }
    

    Even if a dedicated RAII object may be more appropriate in some case (as Mutex).

提交回复
热议问题