سؤال

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?

هل كانت مفيدة؟

المحلول

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.

نصائح أخرى

You cannot declare a database connection or a window or a file on the stack. At least, it's arguable that that is exactly what RAII permits you to do, but without that, you can't.

The point of RAII is that the destructor will be invoked no matter how you exit the scope.

So whether you exit normally or by throwing an exception, your resource will be freed.

BTW, the "resource" doesn't have to be just memory - it can be a file handle, a database connection etc.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top