title: Captured shared_ptr released while executing the lambda body
body: <p>I have a nested lambda in C++, which is to say, an inner lambda contained in a middle lambda, which is also contained in an outer lambda.</p>
  <p>I created a shared_ptr in the outer lambda, which I passed by value to the middle lambda, inside which I created the inner lambda, after declaration of which the captured shared_ptr seems to be released, as can be confirmed with <code>use_count()</code> turning into zero. Why?</p>
  <p>The full code:</p>
  <pre class="lang-cpp prettyprint-override"><code>#include &lt;cstdio&gt;
  #include &lt;functional&gt;
  #include &lt;memory&gt;
  
  struct container;
  using func_type = std::function&lt;void(container&amp;)&gt;;
  struct container {
    explicit container(int id, func_type next) : id{id}, next{next} {
      printf(&quot;contianer (%d)\n&quot;, id);
    }
    func_type next;
    int id;
    ~container() {
      printf(&quot;~contianer (%d)\n&quot;, id);
    }
  };
  
  struct value_type {
    ~value_type() {
      printf(&quot;~value_type\n&quot;);
    }
  };
  
  int main() {
    container c{0, [](container&amp; c1) {
      std::shared_ptr&lt;value_type&gt; value = std::make_shared&lt;value_type&gt;();
      c1 = container{1, [value](container&amp; c2) mutable {
        printf(&quot;value.use_count(): %d\n&quot;, value.use_count());
        c2 = container{2, [](container&amp; c3) mutable {
          printf(&quot;finished\n&quot;);
          return;
        }};
        printf(&quot;value.use_count(): %d\n&quot;, value.use_count());
        return;
      }};
      return;
    }};
    c.next(c);
    c.next(c);
    return 0;
  }
  </code></pre>
  <p>Output: (godbolt: <a href="https://godbolt.org/z/9PbboEPfK" rel="nofollow noreferrer">https://godbolt.org/z/9PbboEPfK</a>)</p>
  <pre><code>Program returned: 0
  Program stdout
  contianer (0)
  contianer (1)
  ~contianer (1)
  value.use_count(): 1
  contianer (2)
  ~value_type
  ~contianer (2)
  value.use_count(): 0
  ~contianer (2)
  </code></pre>