You bark the right tree. Bjarne Stroustrup highly recommends RAII for exception handling, not try / catch / finally. In the latest issue of the C ++ Programming Language (4th edition), he fully expounds his recommended method in Chapter 13, Exception Handling.
It is very difficult to replace an entire chapter, so at first I would recommend just reading the chapter. However, the basic idea is to use composition and allow the designer to protect the resource.
So, if you have a class A that protects 3 resources that everyone can throw up (maybe some memory), you instead let the subobject protect each of its constructor (not constructor A). The key point is that if the constructor is allowed to complete the job, it is guaranteed (by language) that the destructor will be called. So, in the top-level constructor, initialize the subobjects as follows:
class B{ public: B( int n ) {
Imagine that there is a class C and a class D, and they are structured as B. Thus, in your example above, some_state will be protected through a class such as B, C or D.
Another key point. You must protect only one resource in each class of subobjects. Thus, the resource is acquired, and the designer is allowed to exit (in this way, a call is made to the destructor, which will safely release the resource) or he throws (therefore, does not acquire the resource).
source share