Finally in C++

后端 未结 6 1525
南旧
南旧 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

    If for some strange reason you don't have access to the standard libraries, then it's very easy to implement as much as you need of a smart pointer type to handle the resource. It may look a little verbose, but it's less code than those nested try/catch blocks, and you only have to define this template once ever, instead of once per resource that needs management:

    template
    struct MyDeletable {
        explicit MyDeletable(T *ptr) : ptr_(ptr) { }
        ~MyDeleteable() { delete ptr_; }
    private:
        T *ptr_;
        MyDeletable(const MyDeletable &);
        MyDeletable &operator=(const MyDeletable &);
    };
    
    void myfunction() {
        // it's generally recommended that these two be done on one line.
        // But it's possible to overdo that, and accidentally write
        // exception-unsafe code if there are multiple parameters involved.
        // So by all means make it a one-liner, but never forget that there are
        // two distinct steps, and the second one must be nothrow.
        Object *myObject = new Object();
        MyDeletable deleter(myObject);
    
        // do something with my object
    
        return;
    }
    
    
    

    Of course, if you do this and then use RAII in the rest of your code, you'll eventually end up needing all the features of the standard and boost smart pointer types. But this is a start, and does what I think you want.

    The try ... catch approach probably won't work well in the face of maintenance programming. The CLEAN UP block isn't guaranteed to be executed: for example if the "do something" code returns early, or somehow throws something which is not an Exception. On the other hand, the destructor of "deleter" in my code is guaranteed to be executed in both those cases (although not if the program terminates).

    提交回复
    热议问题