RAII

Introduction

Unfortunately, we often overlook cool concepts in programming just because we simply weren’t lucky enough to have stumbled upon them during the course of our work. The blame is ultimately on us, for not searching for simpler solutions to our design problem .. I have no idea what kind of introduction this is, but it is one.

Initialization Is Allocation of Resource

Well, I spelled it backwards .. RAII stands for Resource Allocation Is Initialization. It also means, Resource Destruction Is Release. This principle, as far as I know, has only been widely used by C++ programmers, and after using it a few times, it simplifies resource management greatly, and fits amazingly well with the OOP mantra.

So, what in the name of mother bleep is RAII? Let’s just see a quick example:

{
    Lock lock;

    Data data;
    _vector.push_back(data);
}

What happened?

First, we initialized what looks like an “unused” lock object. Then, we create some data and append it to an instance variable … Doesn’t make much sense without knowing the internals of the Lock object.

The lock object is actually quite simply doing two things:

  1. Acquiring a semaphore/lock on the code section in the constructor
  2. Releasing the semaphore/lock in the destructor

If you think about it in the real world, you bring a lock, and now you have exclusive access to the critical section. after you finish your stuff, the scope will end, and the object destructor will be called automatically, so the lock will be released.

The great thing about this is:

  1. It abstracts the details of how the lock is implemented
  2. It makes perfect sense to OOP developers
  3. It works well even if an exception was thrown in the middle!

Conclusion

Very simple concepts these days, but they are quite interesting for a mainly ObjC/Swift developer diving into the C++ world.