Search code examples
c++raii

Can anyone explain to me the point of RAII?


So, if I understand correctly, the point of RAII is to remove the hassle of memory management. That is, you do the deleting in the destructor of the object. That way, when the pointer goes out of scope, you do not have to worry about deleting it. So here is what I don't understand: why not just declare the variable on the stack in the first place?


Solution

  • There are a few things wrong with your understanding:

    1. The point of RAII is to remove the hassle of resource management, not just memory. For example: A file handle that needs to be closed, a mutex that needs to be unlocked, an object that needs to be released, memory that needs to be freed. Basically, if there is something you have to to when you finish using a resource, that's a good case for RAII.

    2. When a raw C++ pointer goes out of scope, it does nothing. I assume you're talking about a smart pointer which is nothing but an object that wraps around a raw pointer. When that object goes out of scope, its destructor is called and the destructor can be used in turn to free the memory that was allocated in the constructor.

    3. It does not make a difference whether the object that needs to be "released" was allocated on the stack or the heap. The point is that you do something in the constructor when you acquire the resource and you do something else in the destructor when you're finished with it.