Sorry, but I agree with whiteflags that your example is contrived, since you have left out any consideration of the lifetime of file2. Your examples can easily be reorganised as
I would probably organise the enclosed scope into its own function as well, but it is not technically necessary.Code:void FunctionToGiveAnAdditionalContainingScope() { ifstream file2; { // begin the scope as per your example ifstream file1 ("file1.txt"); //read from file1 here file2.open("file2.txt"); //use file1 and file2 here } // use file2 here } // file2 stream's destructor invoked here, so the stream will be closed.
You are certainly correct that programs don't use one resource at at time, and release each resource before using another one. However, every resource is associated with a lifetime, even if lifetimes of distinct resources overlap. There is a point before which the resource is not needed. There is a point at which it is no longer needed. Those two points can be associated with the begin and end of a scope.
Even if a resource has infinite lifetime, it can be associated with a scope. For example, a program that never terminates.
Short of some Armageddon event which (as far as the program is concerned) destroys all reality, some_resource will continue to exist. But it is still associated with a scope.Code:int main() { Resource some_resource; bool reality_exists = true; do { // use some_resource } while (reality_exists); }



1Likes
LinkBack URL
About LinkBacks



