Boost logo

Boost Users :

Subject: Re: [Boost-users] boost::exception_detail::error_info_base does not have virtual destructor
From: Emil Dotchevski (emildotchevski_at_[hidden])
Date: 2011-03-18 18:47:05


On Fri, Mar 18, 2011 at 12:33 PM, Ted Byers <r.ted.byers_at_[hidden]> wrote:
>>From: boost-users-bounces_at_[hidden]
> [mailto:boost-users-bounces_at_[hidden]] On Behalf Of Emil Dotchevski
>>Sent: March-18-11 2:51 PM
>>On Fri, Mar 18, 2011 at 8:55 AM, Ted Byers <r.ted.byers_at_[hidden]> wrote:
>>> The type for the container would be:
>>> std::vector<boost::shared_ptr<base_type> >
>>>
>>> boost::shared_ptr<base_type> and boost::shared_ptr<derived_type> are
>>> two different types.  You can't cast from the one to the other without
>>> writing code to do it.  So, to make one vector containing (smart)
>>> pointers to instances of any or all the derived types, you would have
>>> to cast the pointers to instances the derived types to the base before
>>> you create the shared_ptr.
>>
>>Put the return value from new directly into a shared_ptr -- it'll just
> work!
>
> OK.  Good.  But how?  I am not one to settle for 'it just works'.  Rather, I
> like to dig into code to see precisely how it works.

Shared_ptr remembers the pointer you passed to it, and the destructor
it needs to call, at the time you pass the initial raw pointer to it.
You can step through the destruction code at p.reset() below to see
how it works -- but that shared_ptr<void> will end up calling the foo
destructor:

struct foo { ~foo() { } };

boost::shared_ptr<void> create_foo()
{
  return boost::shared_ptr<foo>(new foo);
}

int main()
{
  boost::shared_ptr<void> p=create_foo();
  p.reset();
}

> The most useful power of runtime polymorphism is based on invokving the
> right virtual functions through base pointers, so I don't see why it is bad
> to use polymorphism when it comes to destruction also.

The way shared_ptr destroys objects is also polymorphic, it just
doesn't use virtual functions. It's actually more powerful than
virtual functions because it doesn't need a virtual function table; as
illustrated, even a shared_ptr<void> can destroy the object correctly.

Emil Dotchevski
Reverge Studios, Inc.
http://www.revergestudios.com/reblog/index.php?n=ReCode


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