Finally in C++

后端 未结 6 1518
南旧
南旧 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:29

    No. The Standard way to build a finally like way is to separate the concerns (http://en.wikipedia.org/wiki/Separation_of_concerns) and make objects that are used within the try block automatically release resources in their destructor (called "Scope Bound Resource Management"). Since destructors run deterministically, unlike in Java, you can rely on them to clean up safely. This way the objects that aquired the resource will also clean up the resource.

    One way that is special is dynamic memory allocation. Since you are the one aquiring the resource, you have to clean up again. Here, smart pointers can be used.

    try {
        // auto_ptr will release the memory safely upon an exception or normal 
        // flow out of the block. Notice we use the "const auto_ptr idiom".
        // http://www.gotw.ca/publications/using_auto_ptr_effectively.htm
        std::auto_ptr const aptr(new A);
    } 
    // catch...
    

提交回复
热议问题