When an element of a list is destroyed I want to iterate through the same list to see if it includes another specific element. This has to happen each time an element is removed.
It works fine if the container is a std::vector but it seem to iterate outside the for-loop and crash if its a std::list.
Is this undefined behavior?
(The following code example works in Visual Studio 2017 but stopped working in Visual Studio 2019)
#include <iostream>
#include <list>
class Element
{
public:
Element(std::list<Element> &list) : list_(list) {}
~Element() {
for (Element& e : list_)
{
std::cout << &e.list_ << std::endl;
}
}
std::list<Element> &list_;
};
int main()
{
std::list<Element> list = { Element(list), Element(list) };
list.clear();
}