CSCE 431 Lecture 10

From Notes
Jump to navigation Jump to search

« previous | Thursday, February 13, 2014 | next »


Design Patterns

Idioms

  • Like design patterns, but a smaller scale
  • Usually language-specific

Example: Resource Acquisition is Initialization (RAII)

class mutex {
    public:
        void lock();
        void unlock();
};

resource shared;
mutex guard;

guard.lock();
// use shared... what if there's an exception?
guard.unlock();
guard.lock();
try {
    // use shared
} catch (...) {
    guard.unlock();
    // do something
}
guard.unlock();

better approach:

template <typename lockee>
class locker {
    public:
        locker(lockee &to_lock) : target(to_lock) {
            target.lock();
        }
        ~locker()  {
            target.unlock();
        }
    private:
        lockee target;
};