new_node->next update in compare_exchange_weak
<p><a href="http://en.cppreference.com/w/cpp/atomic/atomic/compare_exchange" rel="nofollow">http://en.cppreference.com/w/cpp/atomic/atomic/compare_exchange</a></p>

<pre><code>template&lt;typename T&gt;
class stack
{
    std::atomic&lt;node&lt;T&gt;*&gt; head;
 public:
    void push(const T&amp; data)
    {
      node&lt;T&gt;* new_node = new node&lt;T&gt;(data);

      // put the current value of head into new_node-&gt;next
      new_node-&gt;next = head.load(std::memory_order_relaxed);

      // now make new_node the new head, but if the head
      // is no longer what's stored in new_node-&gt;next
      // (some other thread must have inserted a node just now)
      // then put that new head into new_node-&gt;next and try again
      while(!head.compare_exchange_weak(new_node-&gt;next, new_node,
                                        std::memory_order_release,
                                        std::memory_order_relaxed))
          ; // the body of the loop is empty
    }
};
</code></pre>

<p>I have difficulties to understand how the <code>new_node-&gt;next</code> will be automatically pointing to the new head if there is another thread that has inserted a new node. For more generic cases, where the variable <code>head</code> is not necessary a single linked list, how the <code>compare_exchange_weak</code> works in that case?</p>