Boost logo

Boost :

From: Douglas Gregor (gregod_at_[hidden])
Date: 2002-07-17 19:01:46


On Wednesday 17 July 2002 06:28 pm, Ed Brey wrote:
> "Douglas Gregor" <gregod_at_[hidden]> wrote in message
> news:200207171706.05033.gregod_at_cs.rpi.edu...
>
> > This can't be done safely:
> >
> > // Translation unit 1
> > class Foo;
> > boost::shared_ptr<Foo> f; // reference count in shared_ptr
> >
> > // Translation unit 2
> > class Foo : public boost::counted_base
> > {
> > // ...
> > };
> > boost::shared_ptr<Foo> f; // reference count in counted_base
>
> Uh oh. We have this condition in the shared_ptr in Boost 1.28.0 as it is,
> since it avoids the heap allocation when the count exists, even though it
> (AFAIK) doesn't elide the counter pointer yet.
>
> I'm having trouble grasping the ramifications of this problem. It seems
> that this may have been discussed before, but I wonder if I wasn't paying
> close attention. Can you point to or provide an example demonstrating how
> this breaks a program (rather than just pessimizing TU 1)?

Well, it's an ODR violation. The shared_ptr<Foo> in TU #1 will contain a
pointer for the reference count whereas the shared_ptr<Foo> in TU #2 won't
have that same pointer, so we have two classes with the same name and
different semantics.

However, we can detect such problems. Instead of having something like this,
which will cause the above problem:

template<typename T>
class shared_ptr
{
  typedef typename ct_if<has_counted_base<T>::value, IntrusiveImpl<T>,
NonintrusiveImpl<T> >::type Implementation;
// ...
};

We should make the implementation part of the signature, e.g.,

template<typename T,
         typename Implementation = typename ct_if<has_counted_base<T>::value,
                                                  IntrusiveImpl<T>,
                                                  NonintrusiveImpl<T> >::type>
class shared_ptr
{
// ...
};

At least here we can detect the ODR violation, instead of silently creating
broken code that compilers need not diagnose.

        Doug


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk