On Jul 31, 2:26 am, Victor Bazarov <v.Abaza...@comAcast.net> wrote:
subramanian10...@yahoo.com, India wrote:
I wrote the following program for learning purpose only.
[..]
Why is the difference_type not large enough to hold the
distance between any two iterators ?
That's a good question you should most likely be asking the
implementors of the standard library you're using. The
quantities and the types are implementation-defined. Some
implementors *could* decide to use a larger signed type for
'difference_type' just to satisfy that requirement.
Apparently in the particular implementation you use, they
didn't. Why?... How should we know?
Does the implementation actually have a choice? I can't
find any concrete requirement in the C standard saying that
ptrdiff_t must have the same size as size_t, but this would
seem to be the intent. Particularly as the standard says
that subtraction of two pointers is undefined behavior if
the result is not representable in a ptrdiff_t---the
standard explicitly caters to the case in question.
Of course, the code in question dealt with std::vector and a
difference between two iterators. In this case, the C++
standard is somewhat less explicit, but it does say that a
precondition to the expression is "there exists a value n of
Distance such that a + b == b[...]"; in the case in
question, the pre-condition is not met, so the behavior is
undefined.
Logically, of course, the error is using two types, size_t
and ptrdiff_t, rather than just ptrdiff_t. Still, an
implementation could detect the error (although I suspect
that most consider it too rare to be worth the bother), or
simply refuse to allocate a container so large that the
error could occur, making max_size() equal to:
min( numeric_limits< ptrdiff_t >::max(),
numeric_limits< size_t >::max() / sizeof( T ) )