John Gunnarsson a écrit :
> Hi,
>
> I've been working in high level languages (delphi, java, c#) 

C++ could have been added in your list.

> for
> several years and have recently  started to look into c++.
>
> I'ts fairly easy to migrate the "best practices" from other languages
> to c++, but there is one thing that I can't really work out; resource
> cleanup together with exceptions.
>
> In all the above mentioned languages there exist a "finally" clause
> which is used to place cleanup code independent weither an exception
> occured or not, but I cannot find anything similar in C++. The obvous
> thing is to place cleanup code in all catch blocks aswell as after the
> code protected by the try block, something like this (pseudocode)
>
>
> // allocate resource X here
> try
> {
>   // use resource X here
>   // a exception could potenially be raised in the code
>   // above
>
>
>   // --> release resource X --<
>
> }
> catch (exceptiontype1 a)
> {
>   // exceptions error handling for typed exception 1
>
>   // --> release resource X --<
> }
> catch (exceptiontype2 b)
> {
>   // exceptions error handling for typed exception 2
>
>   // --> release resource X --<
> }
>
> As you can see the cleanup code is duplicated 3 times (not very DRY)
> If I would have implemented the same scenario in c# the cleanupcode
> would have been placed in a "finally" clause only once, and would be
> executed wither an exception occured or not.
>
> Since I'm quite new to c++ I'm sure I just missed something very vital
> here, and would like to know how you solve scenarios like this in C++.
>
> //John
>
>   

Depending on how your ressources has been allocated, there is no reason 
to duplicate
the release code (smart pointers is an answer)
C++ use RAII idiom to help you solve your problem.

David.




Reply via email to