Search code examples
c++nullstdlist

What does c++ std::list::front() return with an empty list?


If I have the code:

struct Test
{
  int x = 10;
};

int main()
{
  std::list<Test> linkedList;
  std::cout << linkedList.front().x << std::endl;
}
---

out -> 0

Why do I get 0 for my test.x value? If I change the list to int type, it returns a 0. If I give it a char type, I get nothing (or "").

I am curious how (and why) it happens under the hood. How does it handle returning a value of any type and not exit the program or require a try/catch?


Solution

  • linkedList is an empty list. Calling front() on it leads to UB, means anything is possible.

    Returns a reference to the first element in the container.

    Calling front on an empty container is undefined.