Multiple Inheritance and enable_shared_from_this
In my code base, we use the wonderful enable_shared_from_this template quite frequently. However, I came across an *interesting* problem while mocking some classes for unit tests. I compiled the following code with g++ 4.4.3 and Boost 1.46.1 (the same as the attached code): #include <boost/enable_shared_from_this.hpp> #include <boost/make_shared.hpp> #include <boost/smart_ptr.hpp> #include <iostream> class base : public boost::enable_shared_from_this<base> { public: boost::shared_ptr<base> get_shared_from_base() { return shared_from_this(); } }; class derived : public base, public boost::enable_shared_from_this<derived> { public: boost::shared_ptr<derived> get_shared_from_derived() { return boost::enable_shared_from_this<derived>::shared_from_this(); } }; int main() { boost::shared_ptr<derived> thing = boost::make_shared<derived>(); boost::shared_ptr<derived> derived_thing = thing->get_shared_from_derived(); boost::shared_ptr<base> base_thing = thing->get_shared_from_base(); return 0; } This is what I expect: I expect the get_shared_from_derived call to work, since the _internal_accept_owner would visit it. I would also expect the call to get_shared_from_base to fail with a bad_weak_ptr, since it looks like there is only one call in shared_ptr's constructor. I expect that the actual behavior is probably undefined, since it would depend on which association the compiler feels more strongly about: the enable_shared_from_this<derived> from derived or the enable_shared_from_this<base> from base. What I expect is, of course, not happening, which is why I turn to the Boost gurus. *Neither* of the calls work: they both fail with a bad_weak_ptr. Why would this happen? -- - Travis Gockel
This is what I expect: I expect the get_shared_from_derived call to work, since the _internal_accept_owner would visit it. I would also expect the call to get_shared_from_base to fail with a bad_weak_ptr, since it looks like there is only one call in shared_ptr's constructor. I expect that the actual behavior is probably undefined, since it would depend on which association the compiler feels more strongly about: the enable_shared_from_this<derived> from derived or the enable_shared_from_this<base> from base. What I expect is, of course, not happening, which is why I turn to the Boost gurus. Neither of the calls work: they both fail with a bad_weak_ptr. Why would this happen?
FWIW, with VC10 get_shared_from_base() works correctly (because weak_this_ in enable_shared_from_this<base> is initialized).
participants (2)
-
Igor R
-
Travis Gockel