title: Smart pointers - unique_ptr for a stack-allocated variable
body: <p>I have the following simple code, and I have not found a thread where smart pointers are used for this simple case, but rather copy objects:</p>
  
  <pre><code>int main()
  {
      int i = 1;
  
      std::unique_ptr&lt;int&gt; p1(&amp;i);
      *p1 = 2;
  
      return 0;
  }
  </code></pre>
  
  <p>This results in <code>_BLOCK_TYPE_IS_INVALID</code> when the pointer goes out of scope. If I call <code>p1.release()</code>, the code works fine and I do not get this error. I thought such pointers are smart enough to handle dangling pointers?</p>
  
  <p>An alternative would be if I had a copy of i, which does not give the above error:</p>
  
  <pre><code>std::unique_ptr&lt;int&gt; p1(new int(i));
  </code></pre>
  
  <p>What is the advantage of using smart pointers here, where I do not want to perform the local copy?</p>
  
  <p>If I were to use a raw pointer:</p>
  
  <pre><code>int i = 1;
  int *p1 = &amp;i;
  *p1 = 2;
  </code></pre>
  
  <p>I would not get an error, even if I don't code:</p>
  
  <pre><code>p1 = nullptr;
  </code></pre>