I understand the concept of RAII:
Use the destructor as a means to free resources, such as memory, or closing file handles/database connections. Coming from a Java background this was actually rather easy to understand because of the similarities to finally
.
However, I do not quite understand when you actually should apply it. Obviously it should be implemented when initializing objects on the heap, but what are the other scenarios a normal programmer would have to use it for? Looking at this thread I found out that for example std::ifstream
already has RAII implemented to handle the freeing of its file handle. So wrapping it in another object just to call ifstreamObj.close()
in its destructor would be a waste of time. But I am pretty sure that this is not a general rule that applies to all of the libraries out there.
So my question is: when should I actually use RAII? Is there a general rule of thumb, a best-practice, or do I have to crawl through each and every class's documentation if I want to be sure? Or can I be certain that every class that implements a close()
/free()
/delete()
(or something similar) method also takes care of calling it properly when necessary?
ifstreamObj.close()
in its destructor would be a waste of time" -- True. But if you were holding a reference to anifstreamObj
in a class that also does other things, wouldn't it be nice if that class used its RAII to free theifstreamObj
for you? And when that ifstreamObj was freed, wouldn't it be nice if that object took responsibility for cleaning itself up? – Robert Harvey Apr 21 '17 at 21:20