3 votes by winx — 3 votes, 5 comments

I always found RAII very intuitive and easy to understand. You are often tempted to not do it and you get screwed more often. After over a decade using RAII and sometimes not it never failed me.

What exactly is RAII? Is it only a fancy way to say that when I create an object or a variable it must be initialized at the same time, and that when such object or variable goes out of scope the memory must be automatically freed?

It is a bit more than that. It about objects not variables. Initialisation must happen only in the constructor, no late or lazy init are part of the object. Also deterministic destruction is required. Garbage collection prevents RAII as it is non-deterministic. Everything must be cleaned in the destructor which must be called then leaving score. Many languages cannot provide that.

What's the problem with garbage collectors though? Because they destruct objects only once in a while instead of right after they go out of scope?

Yes, so you don't know when your destructor is called, memory free'd or resources released.