Originally Posted by
King Mir
This is not always possible. consider:
Code:
{
ifstream file1 ("file1.txt");
//read from file1 here
ifstream file2 ("file2.txt");
//use file1 and file2 here
file1.close();
//keep using file 2 here
}
Now you could do this:
Code:
ifstream file2
{
ifstream file1 ("file1.txt");
//read from file1 here
file2.open("file2.txt");
//use file1 and file2 here
}
//keep using file 2 here
But that vialates RAII too.
Streams are the example, but they are not the only resouse that could encounter this problem.
Although this problem isn't that common, I don't think it's invariably a design problem when it does come up.
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
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.
I would probably organise the enclosed scope into its own function as well, but it is not technically necessary.
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.
Code:
int main()
{
Resource some_resource;
bool reality_exists = true;
do
{
// use some_resource
}
while (reality_exists);
}
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.