Armen Tsirunyan
Armen Tsirunyan

Reputation: 133072

vec.erase(vec.end()); Legal?

Can sequential containers erase end?

In the standard it says:

a.erase(q) 
Requires: For vector and deque, T shall be
MoveAssignable.
Effects: Erases the element pointed to by q

It is not clear if a.erase(a.end()) is a no-op or UB for sequential containers. Ideas?

Upvotes: 2

Views: 134

Answers (3)

T.C.
T.C.

Reputation: 137425

§23.2.3 [sequence.reqmts]/p3 (emphasis mine):

In Tables 100 and 101, X denotes a sequence container class, a denotes a value of X containing elements of type T, [...], q denotes a valid dereferenceable const iterator to a.

Table 100 is the sequence container requirements table containing a.erase(q).

In other words, a.erase(a.end()) is UB.

Upvotes: 10

BЈовић
BЈовић

Reputation: 64253

If we use this reference page for erase() :

The iterator pos must be valid and dereferenceable. Thus the end() iterator (which is valid, but is not dereferencable) cannot be used as a value for pos.

So, no - it is not valid.

Upvotes: 5

NathanOliver
NathanOliver

Reputation: 180935

From cplusplus.com: "An invalid position or range causes undefined behavior."

Upvotes: 0

Related Questions