What is the order of clearing items from std :: list?

I want to clear the contents of some std::list. The order in which items are deleted is important to me. According to the output of the next test program, the order is from the first to the last element. Is this guaranteed? This was incomprehensible to me from the C ++ 2003 standard.

#include <list>
#include <iostream>

struct A
{
  A(int i) : I(i) {}
  ~A() { std::cout << I << std::endl; }
  int I;
};

int main()
{
  std::list<A> l;
  l.push_back(A(1));
  l.push_back(A(2));
  l.push_back(A(3));

  std::cout << "clearing list" << std::endl;
  l.clear();
}

ideone link

+5
source share
4 answers

No, it is not defined, and you should not rely on it.

+8
source

No, this is not defined.

The standard only indicates that whenever you call a.clear(), it will be resolved as a.erase(q1,q2), and it will simply indicate that it erases it erases all elements in the range [q1,q2), but does not determine the order in which it will do it.

+3

, ++ 11 sequence containers, std::list. , , , , , , . clear(), erase(), begin() end(), hte ++ 03.

+2

++ 03:

67 - ( )...

a.clear()

/: void erase (begin(), end())

post: size() == 0.

As it begins to remove elements from "begin", I think it is safe to detect that they will be deleted in order. Otherwise, it will be a performance penalty for random access list items.

0
source

All Articles