Subject: [Boost-bugs] [Boost C++ Libraries] #5303: assignment of boost::optional of const reference to a base works incorrectly
From: Boost C++ Libraries (noreply_at_[hidden])
Date: 2011-03-14 06:42:11
#5303: assignment of boost::optional of const reference to a base works
incorrectly
--------------------------------------+-------------------------------------
Reporter: yhirsch@⦠| Owner: fcacciola
Type: Bugs | Status: new
Milestone: To Be Determined | Component: optional
Version: Boost 1.44.0 | Severity: Problem
Keywords: |
--------------------------------------+-------------------------------------
{{{
#include <iostream>
#include <boost/optional.hpp>
class B
{
public:
virtual ~B() { }
virtual void foo() const = 0;
};
class D : public B
{
public:
virtual ~D() { std::cout << "D d-tor (" << this << ")" << std::endl; }
D() { std::cout << "D default c-tor (" << this << ")" << std::endl; }
D(const D& d) : B(d) { std::cout << "D copy c-tor (" << this << ")" <<
std::endl; }
virtual void foo() const { std::cout << "D::foo (" << this << ")" <<
std::endl; }
};
int main(int argc, char** argv)
{
D d;
B& b = d;
boost::optional<const B&> o;
o = d;
o->foo();
}
}}}
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->foo() is called on an invalid object.
If the definition of o is changed to boost::optional<B&> 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).
Alternatively, assigning o = b instead of o = d works fine (because b is
const B&) which is the same type as the template argument of the optional.
-- Ticket URL: <https://svn.boost.org/trac/boost/ticket/5303> Boost C++ Libraries <http://www.boost.org/> Boost provides free peer-reviewed portable C++ source libraries.
This archive was generated by hypermail 2.1.7 : 2017-02-16 18:50:05 UTC