Is copying a range from a container to itself safe or yields runtime error?

85 Views Asked by At

Why in C++ primer is said that we cannot insert to a container a range denoted by iterators to the same range (of the container itself)?

std::list<string> slist{"hi", "there!"};
slist.insert(slist.cbegin(), slist.cbegin(), slist.cend());

for(auto const& s : slist)
    std::cout << s << ' ';
std::cout << '\n';

The output:

hi there! hi there!
  • The program just seems to work fine but in C++ primer 5th ed. it is said to be a "run-time error: iterators denoting the range to copy from. iterator must not refer to the same container as the one we are changing".

  • Is it said that is an error because an insert function will invalidate iterators? If so then why my program seems to work fine?

0

There are 0 best solutions below