Boost C++ Libraries: Ticket #5303: assignment of boost::optional of const reference to a base works incorrectly https://svn.boost.org/trac10/ticket/5303 <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> en-us Boost C++ Libraries /htdocs/site/boost.png https://svn.boost.org/trac10/ticket/5303 Trac 1.4.3 Steven Watanabe Thu, 07 Apr 2011 19:35:54 GMT status changed; resolution set https://svn.boost.org/trac10/ticket/5303#comment:1 https://svn.boost.org/trac10/ticket/5303#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">fixed</span> </li> </ul> <p> This was fixed as a side-effect of <a class="changeset" href="https://svn.boost.org/trac10/changeset/67020" title="Refs #3395. Optional construction and assignment now works correctly ...">[67020]</a>. The fix is in 1.46.0 </p> Ticket