title: Is it possible to override C++11 lambda/closure destructor?
body: <p>I am playing with C++11 lambda/closure feature, trying to write a semi-coroutine (generator) function.</p>
  
  <p>The following codes are my experiment. They works as expected (GCC 4.9/Linux).</p>
  
  <p>I have read several on-line articles introducing C++ lambda/closure, now I understand the lambda function as a functor or function object.</p>
  
  <p>My question is: where can I put the destructor code for closure object? how can I override the default destructor?</p>
  
  <p>I need this function because, some coroutines may request certain system resources when I call the function constructing and returning the closure object (which represents a coroutine). But if the caller function decide to cancel / kill the operation, there should be a mechanism to inform the coroutine object to take some action. The ideal place to put code will be in the destructor, but I cannot find how. </p>
  
  <p>Any suggestions?</p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;functional&gt;
  #include &lt;time.h&gt;
  
  #define CONCAT01(a, b)                      a##b
  #define CONCAT02(a, b)                      CONCAT01(a, b)
  #define YIELD()                             \
    do {                                      \
      CONCAT02(ENTRY, __LINE__):              \
      if (EP == &amp;&amp; CONCAT02(ENTRY, __LINE__)) \
        EP = 0;                               \
      else                                    \
      {                                       \
        EP = &amp;&amp; CONCAT02(ENTRY, __LINE__);    \
        return true;                          \
      }                                       \
    } while (0)
  
  using namespace std;
  
  typedef std::function&lt;bool(void)&gt; coroutine;
  
  coroutine add(int a, int b, int * ret)
  {
    timespec start;
    clock_gettime(CLOCK_REALTIME, &amp;start);
  
    return [=]() mutable -&gt; bool
    {
      timespec now;
      while(1) {
        clock_gettime(CLOCK_REALTIME, &amp;now);
        if (now.tv_sec - start.tv_sec &gt; 1)
          break;
  
        return true;
      }
      * ret = a + b;
      cout &lt;&lt; "add " &lt;&lt; a &lt;&lt; " " &lt;&lt; b &lt;&lt; " equals: " &lt;&lt; a + b &lt;&lt; endl;
      return false;
    };
  }
  
  coroutine sum(int a, int b, int c, int * ret)
  {
    void* EP = 0;
    coroutine co = 0;
    int tmp = 0;
  
    return [=] () mutable -&gt; bool
    {
      if (EP) goto *EP;
  
      co = add(a, b, &amp;tmp);
      while(co())
        YIELD();
  
      co = add(tmp, c, ret);
      while(co())
        YIELD();
  
      return false;
    };
  }
  
  int main()
  {
    int ret;
    coroutine c = sum(1, 2, 4, &amp;ret);
    while (c())
      {
        sleep(1);
        cout &lt;&lt; "wakeup" &lt;&lt; endl;
      }
  
    cout &lt;&lt; "final: " &lt;&lt; ret &lt;&lt; endl;
  
    return 0;
  }
  </code></pre>