Boost logo

Boost :

From: Andrei Alexandrescu (andrewalex_at_[hidden])
Date: 2002-01-11 15:22:40

> I find the whole idea of adding pointer arithmetic to shared_array
> questionable at best and nonsensical at worst.

Cool, but operator[] is kind of closely related to pointer arithmetic, ain't

> That said, if I had to support pointer arithmetic, I'd rather provide the
> full range of operators.

Barring an uber-shared array with owning iterators etc., which I haven't
seen yet and might be cool or not, I believe the intent of shared_array is
to simply provide a reference counted array that calls delete[] on the
original array when exiting the scope.

It all started with my simple remark that if shared_array provides indexing,
it should provide some arithmetic as well. If people use sa[5] they might
just as well use sa + 5. I thought this is a simple fact that reasonable
people would find agreeable.

Then, there are things that are best avoided. For example, you already know
that sa points to the beginning of an array so you want to disable
subtraction of another pointer from it. That is, if sa is a shared_array<T>
and p is a T*, then p - a makes sense but a - p doesn't. (Pointer arithmetic
works only for pointers in the same array).

Then, you may want to disable operator> because there's no sense of testing
whether sa is greater than anything. It is less than or equal to any pointer
you could possibly compare it with.

However, operator<(const shared_array<T>&, const T*), operator<=(const
shared_array<T>&, const T*), operator==(const shared_array<T>&, const T*)
etc. do make sense.

Another operator that you may want to disable is subtraction of unsigned
integers. That is, it doesn't make sense to subtract a positive offset from
a pointer that already points to the /beginning/ of an array.

I guess this all can be enforced at compile time, except for the integral
stuff which is messy.

As it often happens, stronger typechecking tends to render illegal a number
of legal cases. This is ok as long as those cases are seldom useful, and the
type system eliminates a ton of potentially pernicious cases.


Check out THE C++ Seminar: 3 Days with 5 Experts

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