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

Richard Hadsell hadsell at blueskystudios.com
Tue Feb 17 08:28:18 PST 2015


However, the end pointer can never be less than the begin pointer, so you can safely cast the ptrdiff_t result to size_t.  Restricting it to PTRDIFF_MAX seems unnecessarily restrictive.

On 02/16/2015 03:30 AM, Mikael Persson wrote:
> Hi François,
>
> I think you are absolutely correct. And this should definitely be addressed. I think the best would be for you to file a bug report on both libc++ and libstdc++.
>
> Here are a few additional things I would point out:
>
> Note, however, that this only affects vectors with elements of size 1 or less (like vector of bool), because any other type, of size 2 or above, can never have a pointer difference that would overflow ptrdiff_t. So, we are really only talking about char, 
> unsigned char, bool, and empty classes.
>
> I see only one sensible option to address this, which is to restrict max_size() to output the max positive value of ptrdiff_t. Something like this:
>
>     size_type max_size() const noexcept {
>       return ( PTRDIFF_MAX < /* alloc max-size */ ? PTRDIFF_MAX : /* alloc max-size */ );
>     }
>
> It could also be conditional upon sizeof(T) such that this extra step is only done for elements of size 1.
>
> The alternative of accounting for overflow on the calculation of size() would not only have undue overhead on size(), but it would also imply the same precaution be taken everywhere else (in iterators, in most mutating member functions, etc..). And I'm 
> also not sure that this would be standard conforming since the difference_type would no longer be able to represent all iterator differences.
>
> Cheers,
> Mikael.
>
>
> _______________________________________________
> cfe-dev mailing list
> cfe-dev at cs.uiuc.edu
> http://lists.cs.uiuc.edu/mailman/listinfo/cfe-dev

-- 

Dick Hadsell			203-992-6320  Fax: 203-992-6001
Reply-to:			hadsell at blueskystudios.com
Blue Sky Studioshttp://www.blueskystudios.com
1 American Lane, Greenwich, CT 06831-2560

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


More information about the cfe-dev mailing list