If front() returns a reference and the container is empty what do I get, an undefined reference? Does it mean I need to check empty() before each front()?
6 Answers
You get undefined behaviour - you need to check that the container contains something using empty() (which checks if the container is empty) before calling front().
7 Comments
You've always have to be sure your container is not empty before calling front() on this instance. Calling empty() as a safe guard is good.
Of course, depending on your programm design, always having a non-empty container could be an invariant statement allowing you to prevent and save the call to empty() each time you call front(). (or at least in some part of your code?)
But as stated above, if you want to avoid undefinied behavior in your program, make it a strong invariant.
Comments
C++11 N3337 standard draft quote
I just wanted to quickly dig up where it says so in the standard, and I think this is it:
23.2.3 Sequence containers
Expression Operational semantics Container a.front() *a.begin() vector
This says that a.front() is the same as *a.begin(), and we know that *a.begin() on an empty container is undefined.
We know that std::vector is a sequence container from:
23.3.6.1 Class template vector overview
A vector satisfies all of the requirements of a container and of a reversible container, of a sequence container [...]
Also of interest is the non-normative example:
17.3.26 valid but unspecified state
an object state that is not specified except that the object’s invariants are met and operations on the object behave as specified for its type
[ Example: If an object x of type std::vector is in a valid but unspecified state, x.empty() can be called unconditionally, and x.front() can be called only if x.empty() returns false. — end example ]