Prev: "Scoping" variables the middle of their "natural" scope - RAII - is it a good practice?
Next: "Scoping" variables the middle of their "natural" scope - RAII - is it a good practice?
From: Ulrich Eckhardt on 16 Jan 2010 20:20 ManicQin wrote: > In my job I find many times the next "pattern" > > void foo() > { > //some code > { //"re-scoping" > char sTmp[256] = ""; > //some code > } > //some code > } > > sometimes the "re-scoping" was made to keep sTmp in his reservation > and sometimes it's just and old "if scope" that was deleted and the > scopes were left on intention (or not by intention), FYI: The "{...}" is called a block of code. > dropping the scopes will -usually- wont harm the -logical- flow of > the code. I often use such things to lock a resource (mutex) and then release it at a certain point. I do this explicitly to not have the duration of this lock overlap with another lock, which in turn can lead to deadlocks. > (it can cause compile problems because of redefinition but the code > itself will be autonomous) That's a harmless problem, as the compiler will tell you. > When looking on projects and examples in the internet I find more and > more "scoped" classes (RAII), > ScopeGuard, ScopedTimer, ScopedBarrierEnd ,ScopedForking , auto_ptr > (and his many friends) and the list is long... RAII is everywhere, it is an essential C++ technique, unless you are using C++ as a "better C". > (Well you can always add comments ... and hope someone will read them, If the problem is that people don't read comments, then probably the comments are bad. That can include comments like "re-scoping", which only repeat the obvious without giving any information _why_ a separate scope is necessary. > or you can use macros such as > #define SCOPETIMER_START(name) { ScopeTimer name(); > #define SCOPETIMER_END } > but I always find that using such macros to "ugly up" your code...) Interesting macro, as it declares a function. ;) > Is it a good practice to "re-scope"? (RAII classes) > Are there any guide lines for RAII classes? Most such classes can also explicitly end their lifetime, e.g. std::auto_ptr has a reset() function, scoped_lock classes for mutexes often have an explicit unlock(). In any case, the code you quoted is not bad and doesn't have to be refactored. If the separate scope is necessary, there is nothing you can do about it. However, if it isn't obvious why the code might be necessary, that merits a change, or at least a comment. Uli -- [ See http://www.gotw.ca/resources/clcm.htm for info about ] [ comp.lang.c++.moderated. First time posters: Do this! ] |