Hi
I have a question about RAII: If I create an ifstream I know that it will clean itself up once
it goes out of scope since it's a RAII.
(side question: is that the correct way to say it? when something is using the RAII idiom do you say that it's a RAII or that its built using RAII or something else?)
but what if an error occurs before it goes out of scope?
are the resources not freed then?
in which case: what is the point of RAII? if you have to put 'try-catch' blocks around them anyway?
but what if an error occurs before it goes out of scope?
It's irrelevant if an error occurs before it goes out of scope. There's nothing special about an error. You might as well ask "What if I add three to seven before it goes out of scope?"
Some time after that, it will go out of scope, and when it goes out of scope, its destructor is called and whatever tidyup is meant to happen will happen.
What happens when you throw an exception? You go looking for a catch block, and go back up function calls to find it if you have to. That's out of scope. Objects gets destructed.
when something is using the RAII idiom do you say that it's a RAII or that its built using RAII or something else?
No, you just say it has automatic storage duration.
but what if an error occurs before it goes out of scope?
are the resources not freed then?
What do you mean by an "error"? An exception?
You don't have to put try-catch blocks around every instance of RAII you use, or even around every stack frame. As long as the exception is caught anywhere in the call stack, proper destruction will take place. You could even do
1 2 3 4 5 6
int main(){
try{
do_it();
}catch (...){}
return 0;
}
While it will not be terribly useful in terms of error reporting, objects with automatic storage duration will be properly cleaned up if an exception is thrown.
As an aside, 90% of the C++ programmers I've come across happily accept that the term "RAII" has outgrown an original rigid definition or small use-case, and now it covers a much broader range of situations in which an object automatically tidies up neatly after itself in its destructor at end of scope (commonly but by no means always a mirror image of something that happened in a constructor), whether that be closing files or network connections or returning memory or writing some kind of end-of-lifetime log message somewhere or whatever.
But some people, as in the comments thread of this post - https://www.fluentcpp.com/2018/02/13/to-raii-or-not-to-raii/ - get very worked up about using RAII to mean anything other than a very narrowly defined set of situations. Even though we all know what's meant.
If you encounter such people, just nod along and make a note that you need to avoid having certain kinds of conversation with them :)