Programming Languages Debated
Aha! I get it. Excellent example. I can see the self-protection aspect of it, but it seems like those old cartoons where the character ties string on their second finger to remember why they tied the string on their first finger, which was to remind them that they needed to remember something... If you can understand the concept of programming to watch your ass then you should be at the level where you don't program yourself into a corner to begin with. To understand that you're putting in ~MatrixPusher() { glPopMatrix(); } so that you should willfully ignore balancing out the call doesn't make programming any less complicated IMHO.
Making your life easier is always worthwhile. Writing shorter code is always worthwhile. Compare the non-RAAI exception-safe code:
..... is that right? I had to think really hard about it. The RAAI code, I just wrote, and I'm sure it's correct.
[edit]Nope, wasn't right. I forgot the "throw".[/edit]
Code:
void foo()
{
// stuff
glPushMatrix();
try
{
// some GL calls
glPopMatrix();
}
catch (...)
{
glPopMatrix();
throw;
}
// things
}..... is that right? I had to think really hard about it. The RAAI code, I just wrote, and I'm sure it's correct.
[edit]Nope, wasn't right. I forgot the "throw".[/edit]
Yeah, the convenience is nice but the exception handling is the real killer.
Another place it's a total rear-saver is with locking primitives in threading. For example you can do something like this:
Where "Lock" is some class that takes a pointer to a mutex, locks it on construction, and unlocks it on destruction. There's no need to worry at that point if you accidentally didn't unlock the mutex. Though my OS instructor from college would probably also have said that you shouldn't write functions such that you have to worry, to begin with.
But it saves you trouble with exceptions there too.
Another place it's a total rear-saver is with locking primitives in threading. For example you can do something like this:
Code:
void foo() {
Lock lock(&mutex);
....
}Where "Lock" is some class that takes a pointer to a mutex, locks it on construction, and unlocks it on destruction. There's no need to worry at that point if you accidentally didn't unlock the mutex. Though my OS instructor from college would probably also have said that you shouldn't write functions such that you have to worry, to begin with.
But it saves you trouble with exceptions there too.

