<p>I came across <a href="http://www.ddj.com/cpp/184403758" rel="noreferrer">this article</a> written by Andrei Alexandrescu and Petru Marginean many years ago, which presents and discusses a utility class called ScopeGuard for writing exception-safe code. I'd like to know if coding with these objects truly leads to better code or if it obfuscates error handling, in that perhaps the guard's callback would be better presented in a catch block? Does anyone have any experience using these in actual production code?</p>

[{'answer_id': 48663, 'author': 'Konrad Rudolph', 'author_id': 1968, 'author_profile': 'https://Stackoverflow.com/users/1968', 'pm_score': 7, 'selected': True, 'text': "<p>It definitely improves your code. Your tentatively formulated claim, that it's obscure and that code would merit from a <code>catch</code> block is simply not true in C++ because RAII is an established idiom. Resource handling in C++ <em>is</em> done by resource acquisition and garbage collection is done by implicit destructor calls.</p>\n\n<p>On the other hand, explicit <code>catch</code> blocks would bloat the code and introduce subtle errors because the code flow gets much more complex and resource handling has to be done explicitly.</p>\n\n<p>RAII (including <code>ScopeGuard</code>s) isn't an obscure technique in C++ but firmly established best-practice.</p>\n"}, {'answer_id': 48664, 'author': 'Leon Timmermans', 'author_id': 4727, 'author_profile': 'https://Stackoverflow.com/users/4727', 'pm_score': 1, 'selected': False, 'text': "<p>I haven't used this particular template but I've used something similar before. Yes, it does lead to clearer code when compared to equally robust code implemented in different ways.</p>\n"}, {'answer_id': 48786, 'author': '1800 INFORMATION', 'author_id': 3146, 'author_profile': 'https://Stackoverflow.com/users/3146', 'pm_score': 2, 'selected': False, 'text': '<p>I often use it for guarding memory usage, things that need to be freed that were returned from the OS. For example:</p>\n\n<pre><code>DATA_BLOB blobIn, blobOut;\nblobIn.pbData=const_cast&lt;BYTE*&gt;(data);\nblobIn.cbData=length;\n\nCryptUnprotectData(&amp;blobIn, NULL, NULL, NULL, NULL, CRYPTPROTECT_UI_FORBIDDEN, &amp;blobOut);\nGuard guardBlob=guardFn(::LocalFree, blobOut.pbData);\n// do stuff with blobOut.pbData\n</code></pre>\n'}, {'answer_id': 550945, 'author': 'j_random_hacker', 'author_id': 47984, 'author_profile': 'https://Stackoverflow.com/users/47984', 'pm_score': 5, 'selected': False, 'text': '<p>Yes.</p>\n\n<p>If there is one single piece of C++ code that I could recommend every C++ programmer spend 10 minutes learning, it is ScopeGuard (now part of the freely available <a href="http://loki-lib.sourceforge.net/" rel="noreferrer">Loki library</a>).</p>\n\n<p>I decided to try using a (slightly modified) version of ScopeGuard for a smallish Win32 GUI program I was working on.  Win32 as you may know has many different types of resources that need to be closed in different ways (e.g. kernel handles are usually closed with <code>CloseHandle()</code>, GDI <code>BeginPaint()</code> needs to be paired with <code>EndPaint()</code>, etc.)  I used ScopeGuard with all these resources, and also for allocating working buffers with <code>new</code> (e.g. for character set conversions to/from Unicode).</p>\n\n<p><strong>What amazed me was how much <em>shorter</em> the program was.</strong>  Basically, it\'s a win-win: your code gets shorter and more robust at the same time.  Future code changes <em>can\'t leak anything</em>.  They just can\'t.  How cool is that?</p>\n'}, {'answer_id': 33529794, 'author': 'Puppy', 'author_id': 298661, 'author_profile': 'https://Stackoverflow.com/users/298661', 'pm_score': 0, 'selected': False, 'text': "<p>I have to say, no, no it does not. The answers here help to demonstrate why it's a genuinely awful idea. Resource handling should be done through re-usable classes. The only thing they've achieved by using a scope guard is to violate DRY up the wazoo and duplicate their resource freeing code all over their codebase, instead of writing one class to handle the resource and then that's it, for the whole lot.</p>\n\n<p><em>If</em> scope guards have any actual uses, resource handling is <em>not</em> one of them. They're massively inferior to plain RAII in that case, since RAII is deduplicated and automatic and scope guards are manual code duplication or bust.</p>\n"}, {'answer_id': 34716931, 'author': 'j_kubik', 'author_id': 455304, 'author_profile': 'https://Stackoverflow.com/users/455304', 'pm_score': 2, 'selected': False, 'text': "<p>I think above answers lack one important note. As others have pointed out, you can use <code>ScopeGuard</code> in order to free allocated resources independent of failure (exception). But that might not be the only thing you might want to use scope guard for. In fact, the examples in linked article use <code>ScopeGuard</code> for a different purpose: transcations. In short, it might be useful if you have multiple objects (even if those objects properly use RAII) that you need to keep in a state that's somehow correlated. If change of state of any of those objects results in an exception (which, I presume, usually means that its state didn't change) then all changes already applied need to be rolled back. This creates it's own set of problems (what if a rollback fails as well?). You could try to roll out your own class that manages such correlated objects, but as the number of those increases it would get messy and you would probably fall back to using <code>ScopeGuard</code> internally anyway.</p>\n"}, {'answer_id': 40168672, 'author': 'timepp', 'author_id': 2608744, 'author_profile': 'https://Stackoverflow.com/users/2608744', 'pm_score': 2, 'selected': False, 'text': '<p>Yes.</p>\n\n<p>It was so important in C++ that even a special syntax for it in D:</p>\n\n<pre><code>void somefunction() {\n    writeln("function enter");\n    // c++ has similar constructs but not in syntax level\n    scope(exit) writeln("function exit");\n\n    // do what ever you do, you never miss the function exit output\n}\n</code></pre>\n'}, {'answer_id': 64824020, 'author': 'Grim Fandango', 'author_id': 383689, 'author_profile': 'https://Stackoverflow.com/users/383689', 'pm_score': -1, 'selected': False, 'text': '<p>My experience shows that usage of <code>scoped_guard</code> is far inferior to any of the short reusable RAII classes that you can write by hand.</p>\n<p>Before trying the <code>scoped_guard</code>, I had written RAII classes to</p>\n<ul>\n<li>set GLcolor or GLwidth back to the original, once I\'ve drawn a shape</li>\n<li>make sure a file has <code>fclose</code>d once I had <code>fopen</code>ed it.</li>\n<li>reset a mouse pointer to its initial state, after I\'ve changed it to gears/hourgrlass during a execution of a slow function</li>\n<li>reset the <code>sorting</code> state of a QListView\'s back to its previous state, once I\'ve temporarily finished with altering its <code>QListViewItems</code> -- I did not want the list to reorder itself everytime I changed the text of a single item...</li>\n</ul>\n<h1>using simple RAII class</h1>\n<p>Here\'s how my code looked like with my hand-crafted RAII classes:</p>\n<pre class="lang-cpp prettyprint-override"><code>class scoped_width {\n    int m_old_width;\npublic:\n    scoped_width(int w) {\n        m_old_width = getGLwidth();\n        setGLwidth(w);\n    }\n    ~scoped_width() {\n        setGLwidth(m_old_width);\n    }\n};\n\nvoid DrawTriangle(Tria *t)\n{\n    // GLwidth=1 here\n\n    auto guard = scoped_width(2); // sets GLwidth=2\n\n    draw_line(t-&gt;a, t-&gt;b);\n    draw_line(t-&gt;b, t-&gt;c);\n    draw_line(t-&gt;c, t-&gt;a);\n\n    setGLwidth(5);\n\n    draw_point(t-&gt;a);\n    draw_point(t-&gt;b);\n    draw_point(t-&gt;c);\n\n}  // scoped_width sets GLwidth back to 1 here\n</code></pre>\n<p>Very simple implementation for <code>scoped_width</code>, and quite reusable.\nVery simple and readable from the consumer side, also.</p>\n<h1>using <code>scoped_guard</code> (C++14)</h1>\n<p>Now, with the <code>scoped_guard</code>, I have to capture the existing value in the introducer (<code>[]</code>) in order to pass it to the guard\'s callback:</p>\n<pre class="lang-cpp prettyprint-override"><code>void DrawTriangle(Tria *t)\n{\n    // GLwidth=1 here\n\n    auto guard = sg::make_scoped_guard([w=getGLwidth()](){ setGLwidth(w); }); // capture current GLwidth in order to set it back\n    setGLwidth(2); // sets GLwidth=2\n\n    draw_line(t-&gt;a, t-&gt;b);\n    draw_line(t-&gt;b, t-&gt;c);\n    draw_line(t-&gt;c, t-&gt;a);\n\n    setGLwidth(5);\n\n    draw_point(t-&gt;a);\n    draw_point(t-&gt;b);\n    draw_point(t-&gt;c);\n\n}  // scoped_guard sets GLwidth back to 1 here\n</code></pre>\n<p>The above doesn\'t even work on C++11.\nNot to mention that trying to introduce the state to the lambda this way hurts my eyes.</p>\n<h1>using <code>scoped_guard</code> (C++11)</h1>\n<p>In C++11 you have to do this:</p>\n<pre class="lang-cpp prettyprint-override"><code>void DrawTriangle(Tria *t)\n{\n    // GLwidth=1 here\n\n    int previous_width = getGLwidth();  // explicitly capture current width \n    auto guard = sg::make_scoped_guard([=](){ setGLwidth(previous_width); }); // pass it to lambda in order to set it back\n    setGLwidth(2); // sets GLwidth=2\n\n    draw_line(t-&gt;a, t-&gt;b);\n    draw_line(t-&gt;b, t-&gt;c);\n    draw_line(t-&gt;c, t-&gt;a);\n\n    setGLwidth(5);\n\n    draw_point(t-&gt;a);\n    draw_point(t-&gt;b);\n    draw_point(t-&gt;c);\n\n}  // scoped_guard sets GLwidth back to 1 here\n</code></pre>\n<p>As you can see,</p>\n<ul>\n<li><p>the <code>scoped_guard</code> snoppet requires</p>\n<ul>\n<li>3 lines to keep previous value (state) and set it to a new one, and</li>\n<li>2 stack variables (<code>previous_width</code> and <code>guard</code>, again) to hold the previous state</li>\n</ul>\n</li>\n<li><p>the hand-crafted <code>RAII class</code> requires</p>\n<ul>\n<li>1 readable line to set new state and keep the previous one, and</li>\n<li>1 stack variable (<code>guard</code>) to hold the previous state.</li>\n</ul>\n</li>\n</ul>\n<h1>Conclusion</h1>\n<p>I think that examples such as</p>\n<pre><code>void some_function() {\n    sg::scoped_guard([](){ cout &lt;&lt; &quot;this is printed last&quot;; }\n\n    cout &lt;&lt; &quot;this is printed first&quot;;\n}\n</code></pre>\n<p>are no proof of the usefullness of <code>scoped_guard</code>.</p>\n<p>I hope that somebody can show me why I don\'t get the expected gain from <code>scoped_guard</code>.</p>\n<p>I am convinced that RAII can be exploited better by writing short hand-crafted classes, than using the more generic but hard to use <code>scoped_guard</code></p>\n'}]
['https://Stackoverflow.com/questions/48647', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4928/']