c++ std::list::front() return 有什么空列表?

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

如果我有代码:

struct Test
{
  int x = 10;
};

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

out -> 0

为什么我的 test.x 值是 0?如果我将列表更改为 int 类型,它 returns a 0。如果我给它一个 char 类型,我什么也得不到(或“”)。

我很好奇它是如何(以及为什么)在幕后发生的。它如何处理返回任何类型的值而不退出程序或要求 try/catch?

linkedList 是空 list。呼唤front() on it leads to UB,意味着一切皆有可能。

Returns a reference to the first element in the container.

Calling front on an empty container is undefined.