Chaining methods causes data corruption
<p>I have a class structure that looks bit like this:</p>

<pre><code>class Bar
{
public:
    Bar &amp; AddPart(int size, const string &amp; name)
    {
        partitions.insert(pair&lt;string, int&gt;(name,size));
        return *this;
    }
    void PrintParts(ostream &amp; os) const
    {
        map&lt;string, int&gt;::const_iterator it;

        for (it = partitions.begin(); it != partitions.end(); ++it)
        {
            os &lt;&lt; it-&gt;first &lt;&lt; " " &lt;&lt; it-&gt;second &lt;&lt; endl;
        }
    }
private:
    std::map&lt;string, int&gt; parts;
}

class Foo
{
public:
    Foo &amp; AddElement(Bar &amp;a)
    {
        elements.push_back(&amp;a);
        return *this;
    }
private:
    vector&lt;Bar *&gt; elements;
};
</code></pre>

<p>Reason why I return current instance of class is to be able to chain method calling, like this:</p>

<pre><code>Foo f();
f.AddElement(Bar().AddPart(10,"abcd").AddPart(5,"xyz").AddPart(20, "jklm"));
</code></pre>

<p>Problem is, when I call those chained methods and then try to print the data, it is corrupted. Instead of getting getting expected output, which should look like this:</p>

<pre><code>abcd 10
xyz 5
jklm 20
</code></pre>

<p>I get random characters that can't even be displayed.</p>

<p>I tried running it through valgrind, but I got bunch of errors, very similar to this one:</p>

<p><code>Invalid read of size 8
==3347==    at 0x4EC6690: std::basic_ostream&lt;char, std::char_traits&lt;char&gt; &gt;&amp; std::operator&lt;&lt; &lt;char, std::char_traits&lt;char&gt;, std::allocator&lt;char&gt; &gt;(std::basic_ostream&lt;char, std::char_traits&lt;char&gt; &gt;&amp;, std::basic_string&lt;char, std::char_traits&lt;char&gt;, std::allocator&lt;char&gt; &gt; const&amp;) (in /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.17)
</code></p>

<p>How can I fix this?</p>
