Note that there are some explanatory texts on larger screens.

plurals
  1. POAre there cases where a "finally" construct would be useful in C++?
    primarykey
    data
    text
    <p>Bjarne Stroustrup writes in his <a href="http://www.research.att.com/~bs/bs_faq2.html#finally" rel="nofollow noreferrer">C++ Style and Technique FAQ</a>, emphasis mine:</p> <blockquote> <p>Because C++ supports an alternative that is <strong><em>almost always better</em></strong>: The "resource acquisition is initialization" technique (TC++PL3 section 14.4). The basic idea is to represent a resource by a local object, so that the local object's destructor will release the resource. That way, the programmer cannot forget to release the resource. For example:</p> <pre><code>class File_handle { FILE* p; public: File_handle(const char* n, const char* a) { p = fopen(n,a); if (p==0) throw Open_error(errno); } File_handle(FILE* pp) { p = pp; if (p==0) throw Open_error(errno); } ~File_handle() { fclose(p); } operator FILE*() { return p; } // ... }; void f(const char* fn) { File_handle f(fn,"rw"); // open fn for reading and writing // use file through f } </code></pre> <p>In a system, we need a "resource handle" class for each resource. However, we don't have to have an "finally" clause for each acquisition of a resource. In realistic systems, there are far more resource acquisitions than kinds of resources, so the "resource acquisition is initialization" technique leads to less code than use of a "finally" construct.</p> </blockquote> <p>Note that Bjarne writes "almost always better" and not "always better". Now for my question: What situation would a <code>finally</code> construct be better than using the alternative construct (RAII) in C++?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload