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: Ronald Landheer-Cieslak on 16 Jan 2010 20:19 ManicQin wrote: > Hello everybody, > Let me explain what I mean, > > 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), my point is that dropping the scopes will -usually- > wont harm the -logical- flow of the code. > (it can cause compile problems because of redefinition but the code > itself will be autonomous) > > 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... > > Now, when dropping the "re-scoping" of a class I can harm the - > logical- flow of the code. > (Well you can always add comments ... and hope someone will read them, > 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...) > > Is it a good practice to "re-scope"? (RAII classes) > Are there any guide lines for RAII classes? IMO, it really depends on what you're scoping. In the example you provided, there's only an array of chars being "re-scoped", so unless you have another one with the same name a bit further down the road, I don't see a reason to do that. OTOH, scope guards and scoped locks are definitely something you might want to keep in a smaller scope - especially scoped locks. The alternative would be to trigger their "action" (whatever it usually does when it goes out of scope) where your scope would have ended.. I agree on the macro, by the way: they do make the code uglier. In any case, IMO again, scopes like that should be documented in the code. rlc --- news://freenews.netfront.net/ - complaints: news(a)netfront.net --- -- [ See http://www.gotw.ca/resources/clcm.htm for info about ] [ comp.lang.c++.moderated. First time posters: Do this! ] |