Finally in C++

后端 未结 6 1546
南旧
南旧 2020-12-28 08:33

Is this a good way to implement a Finally-like behavior in standard C++? (Without special pointers)

class Exception : public Exception
    { public: virtual          


        
6条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-28 09:27

    The standard answer is to use some variant of resource-allocation-is-initialization abbreviated RAII. Basically you construct a variable that has the same scope as the block that would be inside the block before the finally, then do the work in the finally block inside the objects destructor.

    try {
       // Some work
    }
    finally {
       // Cleanup code
    }
    

    becomes

    class Cleanup
    {
    public:
        ~Cleanup()
        {
            // Cleanup code
        }
    }
    
    Cleanup cleanupObj;
    
    // Some work.
    

    This looks terribly inconvenient, but usually there's a pre-existing object that will do the clean up for you. In your case, it looks like you want to destruct the object in the finally block, which means a smart or unique pointer will do what you want:

    std::unique_ptr obj(new Object());
    
    
    

    or modern C++

    auto obj = std::make_unique();
    
    
    

    No matter which exceptions are thrown, the object will be destructed. Getting back to RAII, in this case the resource allocation is allocating the memory for the Object and constructing it and the initialization is the initialization of the unique_ptr.

    提交回复
    热议问题