Boost C++ Libraries: Ticket #5304: assignment of boost::optional of const reference to a base works incorrectly https://svn.boost.org/trac10/ticket/5304 <pre class="wiki">#include &lt;iostream&gt; #include &lt;boost/optional.hpp&gt; class B { public: virtual ~B() { } virtual void foo() const = 0; }; class D : public B { public: virtual ~D() { std::cout &lt;&lt; "D d-tor (" &lt;&lt; this &lt;&lt; ")" &lt;&lt; std::endl; } D() { std::cout &lt;&lt; "D default c-tor (" &lt;&lt; this &lt;&lt; ")" &lt;&lt; std::endl; } D(const D&amp; d) : B(d) { std::cout &lt;&lt; "D copy c-tor (" &lt;&lt; this &lt;&lt; ")" &lt;&lt; std::endl; } virtual void foo() const { std::cout &lt;&lt; "D::foo (" &lt;&lt; this &lt;&lt; ")" &lt;&lt; std::endl; } }; int main(int argc, char** argv) { D d; B&amp; b = d; boost::optional&lt;const B&amp;&gt; o; o = d; o-&gt;foo(); } </pre><p> The above code compiles and crashes. The reason is the assignment o = d. Apparently, the assignment operator that gets called copies d (since it's passed by value), takes its reference and then the local copy gets destroyed, in which case o-&gt;foo() is called on an invalid object. </p> <p> If the definition of o is changed to boost::optional&lt;B&amp;&gt; the code doesn't compile (I haven't checked the whole code of boost::optional, but I assume this is intentional - in which case it should be the same in the const reference case). </p> <p> Alternatively, assigning o = b instead of o = d works fine (because b is const B&amp;) which is the same type as the template argument of the optional. </p> <p> This was compiled on Fedora 14 x86_64, gcc 4.5.1 with boost 1.44.0. </p> en-us Boost C++ Libraries /htdocs/site/boost.png https://svn.boost.org/trac10/ticket/5304 Trac 1.4.3 Steven Watanabe Thu, 07 Apr 2011 18:29:19 GMT status changed; resolution set https://svn.boost.org/trac10/ticket/5304#comment:1 https://svn.boost.org/trac10/ticket/5304#comment:1 <ul> <li><strong>status</strong> <span class="trac-field-old">new</span> → <span class="trac-field-new">closed</span> </li> <li><strong>resolution</strong> → <span class="trac-field-new">duplicate</span> </li> </ul> <p> Duplicates <a class="closed ticket" href="https://svn.boost.org/trac10/ticket/5303" title="#5303: Bugs: assignment of boost::optional of const reference to a base works ... (closed: fixed)">#5303</a>. </p> Ticket