[cfe-dev] libc++: max_size() of a std::vector

Matt Calabrese rivorus at gmail.com
Tue Feb 17 15:45:14 PST 2015


On Tue, Feb 17, 2015 at 3:22 PM, François Fayard <fayard.francois at icloud.com
> wrote:

> Hi Mikael,
>
> Thanks for the information. I did not realise that as I am quite new to
> C++. I am coming from a Fortran background which is why indices mean so
> much to me :-)
>
> For the bug report, it turns out that I’ve done more tests. For
> std::vector<char>
> - libc++ version 3.5 has been fixed and max_size() returns PTRDIFF_MAX
> - libstdc++ version 4.9.2 is buggy and returns SIZE_MAX
> - Visual Studio 2013 is buggy and returns SIZE_MAX
> So libc++ is safe and I’ll fill a bug report against the other standard
> libraries.
>
> From the very beginning, my feeling is that this choice of using
> std::size_t for indices is a *very* bad decision for various reasons:
> comparing signed and unsigned integers is like shooting yourself in the
> foot, compilers can’t optimize anything with unsigned integers because it
> must assume modulo 2^n arithmetic, etc. The only explanation I had for this
> choice was that in the old days of 16 bit computers 1 bit was a big
> difference in between std::size_t and std::ptrditt_t. Now, even this
> historical reason is falling apart.


I take a somewhat opposite position -- the problem isn't that size is
unsigned. The size being unsigned properly matches the set of possible
sizes (a size cannot be negative). The problem, IMO, is that our only way
of calculating the difference between pointer values assumes that we may be
doing something like A - B in a situation where A < B, and so that
operation yields an instance of a signed type. In generic algorithms, I do
not know of situations where you are doing subtraction of pointer values
where you don't already know that one iterator is greater than or equal to
another. Calculating the size of a vector is a good example of this, as
when doing end() - begin(), you know that end() >= begin(). Rather, if we
simply had a way in the language (or more likely, via a standard library
function with an implementation that's not fully specified in the standard)
to calculate the difference between pointers in a way that yielded a size_t
rather than a ptrdiff_t, with the precondition of the relative order of the
operands, then we would arrive at a solution that doesn't require having a
size() function that returns a type that can represent negative values.

-- 
-Matt Calabrese
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.llvm.org/pipermail/cfe-dev/attachments/20150217/6a1901bd/attachment.html>


More information about the cfe-dev mailing list