Possible Duplicate:
Scope with Brackets in C++
I’m dealing with v8 javascript engine, developing a learning enviroment for new students in my university, and i step up with this:
d8.cc:309
char* input = NULL;
{ // Release lock for blocking input.
Unlocker unlock(isolate);
input = fgets(buffer, kBufferSize, stdin);
}
- What’s its name?
- How can I use it in other contexts?
- Is only fair in c++?
The overall structure (i.e. an unnamed block) is known as a compound-statement as far as the language standard is concerned. It serves to introduce a new scope.
In C++, there are generally two uses for this:
To limit a local variable to a particular section of code; the aim being to minimise scope “pollution”, and to make it easier for the reader of the code. (The same can be achieved in other languages, like C and Java.)
Tightly controlling the lifetime of an object/resource, because the destructor of scope-local variables will be automatically called at the end of the scope. This can be used for several clever things, e.g. automatically closing file handles, releasing mutexes, and so on. So you may hear people talk about e.g. scoped mutexes. (C and Java don’t have destructors, so this concept doesn’t translate.)