What do I get from front() of empty std container?

C++Stl

C++ Problem Overview


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()?

C++ Solutions


Solution 1 - C++

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().

Solution 2 - C++

You get undefined behaviour.

To get range checking use at(0). If this fails you get a out_of_range exception.

Solution 3 - C++

Yes, you can use 'at' like Graham mentioned instead of using front.

But, at(0) is only available for some containers - vectors, deque and not for others - list, queue, stack. In these cases you've to fall back on the safety of the 'empty' check.

Solution 4 - C++

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.

Solution 5 - C++

Undefined Behaviour

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionjackhabView Question on Stackoverflow
Solution 1 - C++anonView Answer on Stackoverflow
Solution 2 - C++graham.reedsView Answer on Stackoverflow
Solution 3 - C++Arun RView Answer on Stackoverflow
Solution 4 - C++yves BaumesView Answer on Stackoverflow
Solution 5 - C++anilView Answer on Stackoverflow