Boost logo

Boost :

From: Peter Dimov (pdimov_at_[hidden])
Date: 2004-01-21 15:38:27


Howard Hinnant wrote:
>
> I'm still flopping like a fish out of water on this one! :-)
>
> I ran the following experiment on my system (32 bit flat address
> space):
>
> #include <memory>
> #include <iostream>
>
> int main()
> {
> char* p1 = new char [0x80000001];
> p1[0x80000000] = char(0x5A);
> std::cout << (int)(p1[-2147483648]) << '\n';
> std::cout << (int)(p1[0x80000000]) << '\n';
> std::cout << (int)(p1[2147483648]) << '\n';
> delete [] p1;
> //
> Metrowerks::move_ptr<char[]> p2(new char [0x80000001]);
> p2[0x80000000] = char(0x5A);
> std::cout << (int)(p2[-2147483648]) << '\n';
> std::cout << (int)(p2[0x80000000]) << '\n';
> std::cout << (int)(p2[2147483648]) << '\n';
> }
>
> I ran this with move_ptr::operator[] using size_t and ptrdiff_t.
> Because my system uses two's complement, it works no matter what. And
> fortunately my system's virtual memory manager is good enough to deal
> with a 2GB allocation! Note though that if in my ptrdiff_t version I
> had assert(i >= 0) then my experiment would have asserted rather than
> run correctly.
>
> So do we have sufficient motivation to artificially restrict array
> sizes in move_ptr to numeric_limits<ptrdiff_t>::max()? Assuming we
> don't (and so we can not assert(i >= 0)), then are there any other
> advantages ptrdiff_t might have over size_t? I'm flopping back over
> to size_t just because it seems more intuitive (even though ptrdiff_t -
> non assert checked - seems to work just as well).

Not giving up easily. :-)

T & operator[] ( size_t i ) const;

Returns: *(get() + i)

No opportunity to assert since you don't know the size of the block.

T & operator[] ( ptrdiff_t i ) const;

Requires: i >= 0
Returns: *(get() + i)

Since i < 0 is undefined behavior, you (the implementor) now have the choice
of assert()ing or defining it so that negative indices wrap around as in the
size_t case (in case ptrdiff_t can't hold all size_t values and large arrays
are more important than catching errors).


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