Note that there are some explanatory texts on larger screens.

plurals
  1. POMaking a non-object resource RAII-compliant
    primarykey
    data
    text
    <p>in my code I use <code>HANDLE</code>s from <code>windows.h</code>. They are used like</p> <pre><code>HANDLE h; if (!openHandleToSomething(arg1, arg2, &amp;h)) { throw std::exception("openHandleToSomething error"); } /* Use the handle in other functions which can throw as well */ if (!CloseHandle(h)) { throw std::exception("closeHandle error"); } </code></pre> <p>As you see, you have to insert this <code>CloseHandle</code> to every exception which can happen in the middle of acquiration and release. Therefore, it's likely you forget one (or there is a fancy SEH exception which you didn't know about) and voilà, you have your memory leak.</p> <p>Recently, I've read about RAII which should remove the headaches from such cases and should call this <code>CloseHandle</code> automatically. I've also seen that there is something like <code>std::auto_ptr&lt;someType&gt;</code> in C++ which solves the problem for resources which were allocated with <code>new</code>.</p> <p>However, since I don't use <code>new</code> and since <code>HANDLE</code> is just <code>typedef</code>ed to be a <code>void *</code>, I wonder how I should use the <code>std::auto_ptr&lt;someType&gt;</code>. Somehow, it should be possible to give it a custom deleter function (<code>if (!CloseHandle(h)) { throw std::exception("closeHandle error"); }</code>). Creating a class would be another method since the destructor gets called any time an instance of it gets out of scope. However, it's just overkill to have a class for every simple thing.</p> <p>How can I fix these accidential memory leaks?</p> <p>Note that I would prefer solutions which are in pure C++ with no libraries and big dependencies except if they are really small and used in most of the environments anyways.</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.
    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