Call a function before function exits

前端 未结 5 887
抹茶落季
抹茶落季 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:35

    What's wrong with writing your own generic resource wrapper?

    template >
    class resource_mgr
    {
        Res* resource;
        Fn initialize, finalize;
    
    public:
        resource_mgr (Res* r, Fn i, Fn f)
        : resource(r),
          initialize(i),
          finalize(f)
        {
            initialize(resource);
        }
    
        resource_mgr (resource_mgr const&) = delete;
        resource_mgr (resource_mgr&&)      = delete;
    
        resource_mgr const& operator = (resource_mgr const&) = delete;
        resource_mgr const& operator = (resource_mgr&&)      = delete;
    
        ~resource_mgr
        {
            try
            {
                finalize(resource);
            }
            catch(...)
            {
                std::cerr << "Uh-oh!"
            }
        }
    };
    

    You can keep it simple or go wild on something like this -- use smart pointers, define move operations, add support for custom error handlers, etc. You might use it like this:

    void threadfunc_autolock(int i, float value)
    {
        resource_mgr  autoMutex (
            &myMutex,
            [](auto* p) { if (!pthread_mutex_lock(p)) throw Something(); },
            [](auto* p) { if (!pthread_mutex_unlock(p)) throw Something(); }
        );
    
        /* . . . */
    }
    

提交回复
热议问题