title: Passing shared_ptr to lambda by value leaks memory
body: <p>I have the following code :</p>
  
  <pre><code>void MyClass::onOpenModalBtnClicked() {
      uiManager-&gt;load(L"data/ui/testmodal.json");
      std::shared_ptr&lt;UIElement&gt; modal = uiManager-&gt;getElementById("loginModal");
  
      if(modal) {
          modal-&gt;getElementById("closeButton")-&gt;onClicked = [modal]() {
              modal-&gt;hide();
          };
      }
  }
  </code></pre>
  
  <p>This works fine and the modal is closed when the button is clicked, <code>onClicked</code> is a <code>std::function</code>.</p>
  
  <p>I also have this at the beginning of my app :</p>
  
  <pre><code>#if defined(DEBUG) | defined (_DEBUG)
      _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
  #endif
  </code></pre>
  
  <p>This prints out memory leaks when the app terminates.</p>
  
  <p>With the above code I get lots of memory leaks, if I change the code to the below they are all gone :</p>
  
  <pre><code>void MyClass::onOpenModalBtnClicked() {
      uiManager-&gt;load(L"data/ui/testmodal.json");
      std::shared_ptr&lt;UIElement&gt; modal = uiManager-&gt;getElementById("loginModal");
  
      if(modal) {
          modal-&gt;getElementById("closeButton")-&gt;onClicked = [this]() {
              uiManager-&gt;getElementById("loginModal")-&gt;hide();
          };
      }
  }
  </code></pre>
  
  <p>I am assuming passing in the <code>shared_ptr</code> by value increases the ref count by 1 and then this reference never goes out of scope or it goes out of scope after the mem leaks are reported. So I tried to call reset inside the lambda after I used the shared_ptr but then I get this compiler error :</p>
  
  <p><code>Error  1   error C2662: 'void std::shared_ptr&lt;_Ty&gt;::reset(void) throw()' : cannot convert 'this' pointer from 'const std::shared_ptr&lt;_Ty&gt;' to 'std::shared_ptr&lt;_Ty&gt; &amp;'
  </code></p>
  
  <p>So the question is how can I use the captured <code>modal</code> and not get those memory leaks?</p>
  
  <p><strong>Edit:</strong> 
  So I got rid of the compile error by adding <code>mutable</code> to the lambda.</p>
  
  <pre><code>if(modal) {
      modal-&gt;getElementById("closeButton")-&gt;onClicked = [modal]() mutable {
          modal-&gt;hide();
          modal.reset();
      };
  }
  </code></pre>
  
  <p>Now if I click the close button, and close the app there are no memory leaks, since the reset cleans that reference. But if the button is never clicked I still get the leaks.</p>