title: segmentation fault at runtime using future c++
body: <p>I am getting a segmentation fault on the commented instruction at the end of the code snippet during runtime.
  Did I use properly the future? The queue works(seems to work) fine in single thread. When I try popping the element asynchronously, I get a segmentation fault.</p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;memory&gt;
  #include &lt;atomic&gt;
  #include &lt;thread&gt;
  #include &lt;future&gt;
  #include &lt;assert.h&gt;
  using std::cout;
  
  template&lt;typename T&gt;
  class Queue
  { private:
      struct element
      {
        T data;
        element* previous;
        element():previous(nullptr){}
      };
  
      std::atomic&lt;element*&gt; head;
      std::atomic&lt;element*&gt; tail;
    public:
      Queue():head(new element), tail( head.load() ){}
  
      ~Queue()
      {
        while( element* const old_head = head.load() )
        {
          head.store(old_head-&gt;previous);
          delete old_head;
        }
      }
  
      T* pop()
      {
        element* old_head = head.load();
        if( old_head == tail.load() ){return nullptr;}
  
        head.store( old_head-&gt;previous );
  
        T* const result = new T(old_head-&gt;data);
        delete old_head;
        return result;
      }
  
      void push(T new_value)
      {
        element* new_data = new element;
        new_data-&gt;data = new_value;
  
        element* const old_tail = tail.load();
        std::swap(old_tail-&gt;data, new_value);
  
        element* p = new element;
        old_tail -&gt; previous = p;
        tail.store(p);
        assert( tail.load() != head.load() );
      }
  
   };
  
  int main()
  {
    Queue&lt;double&gt; aDoubleQueue;
  
    assert( nullptr == aDoubleQueue.pop() );
    aDoubleQueue.push(17.0);
    assert( 17.0 == *aDoubleQueue.pop() );
    aDoubleQueue.push(17.0);
    aDoubleQueue.push(19.0);
    assert( 17.0 == *aDoubleQueue.pop() );
    assert( 19.0 == *aDoubleQueue.pop() );
    assert( nullptr == aDoubleQueue.pop() );
  
    aDoubleQueue.push(17.0);
    std::future&lt; double* &gt; popped = std::async(&amp;Queue&lt;double&gt;::pop, &amp;aDoubleQueue );
    popped.wait();  
    if( nullptr == popped.get()){ cout &lt;&lt; "\n nullptr";}
    else
    { cout &lt;&lt; "\n !nullptr";
      // double* a = popped.get(); // causes a segmentation fault
    }
    return 0;
  }
  </code></pre>