Note that there are some explanatory texts on larger screens.

plurals
  1. PODoes the standard behavior for deleters differ between shared_ptr and unique_ptr in the case of null pointers?
    primarykey
    data
    text
    <p>OK, so first some things that might be relevant:</p> <p>I'm using the Clang 3.1 compiler, in C++11 mode, with the standard library set to libc++.</p> <p>I'm trying to familiarize myself with C++11, and in so doing I ran across behavior that seems odd. It may be a quirk of Clang or libc++ but I can't speak C++ standardese and I have no access to other compilers with C++11 support so I can't really check it, and I've searched the internet and Stack Overflow to the best of my ability without finding anything related...so here we go:</p> <p>When using shared_ptr / unique_ptr to implement RAII for a simple resource, it seems that their behavior differs with respect to null pointers upon deletion. I realize that normally it's not necessary to delete a null pointer, but I had expected the behavior to at least match between the two STL smart pointers.</p> <p>For the specific case, consider the following code:</p> <pre><code>{ auto Deleter = [](void *){cout &lt;&lt; "It's later!" &lt;&lt; endl;}; shared_ptr&lt;void&gt; spDoSomethingLater(nullptr, Deleter); unique_ptr&lt;void, void (*)(void *)&gt; upDoSomethingLater(nullptr, Deleter); cout &lt;&lt; "It's now!" &lt;&lt; endl; } </code></pre> <p>I would have expected one of the following outputs from this:</p> <p>a) If both deleters are called even though the pointer is null:</p> <pre><code>"It's now!" "It's later!" "It's later!" </code></pre> <p>b) If neither deleter is called because the pointer is null:</p> <pre><code>"It's now!" </code></pre> <p>But I observe neither of these cases. Instead, I observe:</p> <pre><code>"It's now!" "It's later!" </code></pre> <p>Which means one but not the other of the deleters is being called. Upon further investigation, I found that the deleter for shared_ptr is called regardless of whether it holds a null value, but unique_ptr's deleter is only called if it does not hold a null value.</p> <p>My questions: Is this actually the correct behavior as specified by the standard? If so, why does the specified behavior differ between the two STL types in this manner? If not, is this a bug I should report to libc++?</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