Memory corruption in a small ref-counted buffer class
<p>I have a simple reference counted class that holds a memory buffer. It looks like this:</p>

<pre><code>#include &lt;algorithm&gt;

template&lt;typename T&gt;
struct buffer
{
    // create a buffer of length n
    buffer(unsigned n) : rc(*(new unsigned(1))), data(new T[n]) { }

    buffer(const buffer&lt;T&gt; &amp; rhs) : rc(++rhs.rc), data(rhs.data) { }

    buffer&lt;T&gt;&amp; operator=(buffer&lt;T&gt; rhs)
    {
        std::swap(rc, rhs.rc);
        std::swap(data, rhs.data);
        return *this;
    }

    ~buffer()
    {
        if (--rc == 0) {
            delete [] data;
            delete (&amp;rc);
        }
    }

private:
    mutable unsigned &amp; rc;
    T * data;
};


int main() {
    typedef buffer&lt;int&gt; numbers;
    numbers n1(10);
    numbers n2(20);
    numbers n3(30);
    n1 = n2 = n3 = n2;
}
</code></pre>

<p>I don't see anything wrong with the code. However Visual Studio and valgrind complain about memory corruption.</p>

<p>I've stared at this code for way too long now. Can anyone spot the error?</p>
