Title
Iterator operator-= has gratuitous undefined behaviour
Status
c++17
Section
[random.access.iterators]
Submitter
Hubert Tong

Created on 2015-07-15.00:00:00 last changed 89 months ago

Messages

Date: 2016-08-02.17:19:11

Proposed resolution:

This wording is relative to N4527.

  1. Change Table 110 "Random access iterator requirements (in addition to bidirectional iterator)" as indicated:

    Table 110 — Random access iterator requirements (in addition to bidirectional iterator)
    Expression Return type Operational
    semantics
    Assertion/note
    pre-/post-condition
    r -= n X& return r += -n; pre: the absolute value of n is in the range of representable values of difference_type.
Date: 2016-08-02.17:19:11

[ 2016-08, Chicago ]

Monday PM: Move to Tentatively Ready

Date: 2015-07-15.00:00:00

In subclause [random.access.iterators], Table 110, the operational semantics for the expression "r -= n" are defined as

return r += -n;

Given a difference_type of a type int with range [-32768, 32767], if the value of n is -32768, then the evaluation of -n causes undefined behaviour (Clause 5 [expr] paragraph 4).

The operational semantics may be changed such that the undefined behaviour is avoided.

Suggested wording:

Replace the operational semantics for "r -= n" with:

{ 
  difference_type m = n;
  if (m >= 0)
    while (m--)
      --r;
  else
    while (m++)
      ++r;
  return r; 
}

Jonathan Wakely:

I'm now convinced we don't want to change the definition of -= and instead we should explicitly state the (currently implicit) precondition that n != numeric_limits<difference_type>::min().

History
Date User Action Args
2017-07-30 20:15:43adminsetstatus: wp -> c++17
2016-11-14 03:59:28adminsetstatus: pending -> wp
2016-11-14 03:55:22adminsetstatus: ready -> pending
2016-08-02 17:19:11adminsetmessages: + msg8331
2016-08-02 17:19:11adminsetstatus: new -> ready
2015-08-17 18:24:27adminsetmessages: + msg7489
2015-07-15 00:00:00admincreate