ERROR: The requested URL could not be retrieved (yeah, site didn’t work when i clicked on it from RSS).
Matt uses this bit of ruby code to demonstrate that here you can’t ever not close the file handle:
File.open('something.txt') do |fd|
# Manipulate the file through 'fd'
end
# File handle is now closed
Which seems pretty cool. However, a good C++ programmer can also acheive the same (or better) things!
For example, in NDB (well, in the portability library we use inside NDB) we have a class called Guard. The constructor for Guard pthread_mutex_locks a mutex. The destructor unlocks it. So, for when you’ve got some simple mutual exclusion you need doing, you can have bits of code like this:
{
Guard g(m_config_mutex);
if(m_config.foo<10)
return -1;
// other_stuff
}
Guess what, those nice little error checking bits that should just return -1 look a lot cleaner and you can never forget to unlock the mutex! You’ll see code like this in the management server (ndb_mgmd – source in storage/ndb/src/mgmsrvr/ mostly in MgmtSrvr.cpp).
In fact, you can do this with files as well (multiple ones)Â and have them all closed on exit from the block. It’s all a matter of having (or writing) some good classes. I’m no Ruby expert – but I think you’d have to have more indentation to do that with two files?