Note that there are some explanatory texts on larger screens.

plurals
  1. POMaking a HANDLE RAII-compliant using shared_ptr with a custom deleter
    primarykey
    data
    text
    <p>I've recently posted a general question about RAII at <a href="https://stackoverflow.com/questions/1556168/making-a-non-object-resource-raii-compliant">SO</a>. However, I still have some implementation issues with my HANDLE example.</p> <p>A <code>HANDLE</code> is typedeffed to <code>void *</code> in <code>windows.h</code>. Therefore, the correct <code>shared_ptr</code> definition needs to be </p> <pre><code>std::tr1::shared_ptr&lt;void&gt; myHandle (INVALID_HANDLE_VALUE, CloseHandle); </code></pre> <p><strong>Example 1</strong> <code>CreateToolhelp32Snapshot</code>: returns <code>HANDLE</code> and works.</p> <pre><code>const std::tr1::shared_ptr&lt;void&gt; h (CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL), CloseHandle); </code></pre> <p>As I use <code>void</code> in the definition (what is the correct way?) problems go on, when I try to call some more winapi commands with this pointer. They functionally work, but are ugly and I am sure that there has to be a better solution.</p> <p>In the following examples, <code>h</code> is a pointer which was created via the definition at the top.</p> <p><strong>Example 2</strong> <code>OpenProcessToken</code>: last argument is a <code>PHANDLE</code>. medium ugly with the cast.</p> <pre><code>OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, (PHANDLE)&amp;h); </code></pre> <p><strong>Example 3</strong> <code>Process32First</code>: first argument is a <code>HANDLE</code>. REALLY ugly.</p> <pre><code>Process32First(*((PHANDLE)&amp;h), &amp;pEntry); </code></pre> <p><strong>Example 4</strong> simple comparison with a constant <code>HANDLE</code>. REALLY ugly.</p> <pre><code>if (*((PHANDLE)&amp;h) == INVALID_HANDLE) { /* do something */ } </code></pre> <p>What is the correct way to create a proper shared_ptr for a HANDLE?</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