Boost logo

Boost :

From: Andy Glew (glew_at_[hidden])
Date: 1999-11-09 23:54:38

> >Hmm. I had assumed that this
> >
> > a == b
> >
> >would compare the pointers and this
> >
> > *a == *b
> >
> >would compare the objects.
> Perhaps I should have elaborated. What if, for example,
> you wanted to maintain a sorted vector of these shared
> pointers? You *could* still do it your way by creating
> a comparison function/functor and using it for the sort
> and for every call to find(), etc. But isn't it nicer
> to be able to define the operators == and < etc and use
> the non-comparison-function-expecting versions of all
> the calls?

You are basically talking about having the smart_ptr<T>
act like a smart reference, i.e. to have value semantics
and not pointer semantics, at least with regards to ==.

It is unfortunate that C++ does not allow overriding of
operator.(), so that value syntax could be used uniformly.
Unfortunately, . cannot be overloaded, so we must always
use -> to access members.

Anyway... I have been experimenting with value vs. ptr syntax
for my own smart pointers. It's a slippery slope.

I very much do like being able to say
    a = b.
Oh, yeah, you already get that with shared_ptr<T> assignment
(one of my smart_ptrs is a degenerate pointer that always allocates
on assignment - I call it coa_ptr<T>, copy on access.)

Then you have to decide about
    a == b vs *a == *b
    other comparisons a < b
    other operators a + b vs *a + *b
    implicit conversions
            smart_ptr<T>::operator T& ()
            vs smart_ptr<T>::operator T* ()

Overall, value semantics is quite nice, except for the annoying
requirement to use operator->() for member access.

Here's a benefit that I have not seen mentioned: by defining smart pointers
with value semantics and syntax, I have been able to use exactly the same text
for templates as for manipulating dynamically polymorphic data structures
using abstract base classes.

To acheive this, I have a template pointerize<T> that maps operator->()
to operator.(), and similarly for operator*() --- i.e. that makes a value look
syntactically like a pointer for member access.)

This is a gross hack, but I like anything that reduces the amount of coe that needs
to get written. It still looks strange, though.

Anyway, I think that you need both value and pointer semantics.

0) if you are only going to have one, make it be pointer semantics,
    i.e. *a == *b. More familiar to C++ programmers.

1) if you are going to have value semantics, go all the way

    define a template wrapper and/or mixin that converts a
    pointer syntax/semantic to a value syntax/semantic.

Boost list run by bdawes at, gregod at, cpdaniel at, john at