3 ms·
ScopeGuards as imagined here (Facebook's folly library has one) are near-essential for writing reasonable systems code in C++. int fd = socket(...); if (
by alexgartrell 9y ago
ScopeGuards as imagined here (Facebook's folly library has one) are near-essential for writing reasonable systems code in C++.
int fd = socket(...);
if (fd < 0) return false;
SCOPE_EXIT { ::close(fd); };
if (ioctl(fd, ...) != 0) return false;
if (ioctl(fd, ...) != 0) return false;
...
return true;
You could totally just write the FdWrapper class, but then you're still a user handling resource cleanup, but with more lines.
- ot 9y ago> You could totally just write the FdWrapper class Which, BTW, is exactly what folly::File does :)
- bodyfour 9y ago> You could totally just write the FdWrapper class Yes, and that RAII class would be reusable all of the places you need to close a file descriptor. It's even a handy place to hang more methods that work on the descriptor... for instance if you wanted to abstract those ioctls. That's why I personally never use ScopeGuards in C++. You are correct that writing a single-use RAII class requires a few lines of extra code. However I have found that after I write such a class I often find myself using it over and over.