Of course, this is a good practice. It explicitly limits the use of this variable. I do this quite often. This definition is also used to force the start of some object destructors.
For instance:
std::vector<int> v; v.resize( 10 );
How do you clear this memory? There is no function to call or any way to manually specify the vector v to clear its memory. The solution is to force it to go out of scope (assuming I used swap correctly):
std::vector<int> v; v.resize( 10 );
Another common use is in switching cases. Often I need to create a temporary variable in the switch:
switch( val ) { case constant: { int x = 10;
The last place I can recall from my head is writing scripts for some kind of code. When unit testing often happens, I just want to write my test code as quickly as possible without spending a lot of time on dev-time. So, I put a bunch of related tests in one function, but complete local variables in separate areas to make sure that I don't hit any weird errors (possibly exchanging iterators through tests).
source share