Boost logo

Boost Users :

Subject: [Boost-users] Multiple Inheritance and enable_shared_from_this
From: Travis Gockel (travis_at_[hidden])
Date: 2011-07-28 15:54:28


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




Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net