Boost logo

Boost :

From: Howard Hinnant (hinnant_at_[hidden])
Date: 2004-01-21 14:49:12


On Jan 21, 2004, at 10:41 AM, Peter Dimov wrote:

> Yes, shared_array can be extended that way. But my point was much
> simpler:
> you can assert(i >= 0) in operator[](ptrdiff_t i) to catch s[-1], but
> you
> can't if i is size_t, and s[-1] still works. :-)
>
> (Of course you can assert(i < SIZE_T_MAX / 2) but that's just dancing
> around.)
>
> The only reason size_t works for vector is that vector knows its
> size(), so
> it can assert(i < size()) and catch negative indices for free.

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).

-Howard


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