0

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?

Itachi Uchiwa
  • 3,044
  • 12
  • 26
  • 5
    According to [cppreference](https://en.cppreference.com/w/cpp/container/list/insert) it's undefined behavior if you attempt to insert a list into itself. "Appearing to work correctly" is, of course, one possible outcome of undefined behavior. – Nathan Pierson Oct 07 '21 at 00:10
  • 3
    When you break the rules, you often get Undefined Behavior. That means the program doesn't have to produce an obvious error message, it can even appear to work. When it appears to work, it is usually just bad luck, and it can stop working at any time for no obvious reason or your program may run fine for a while and crash somewhere else. You got unlucky. In C++ it is not possible to demonstrate by example that code is valid. – François Andrieux Oct 07 '21 at 00:10
  • 1
    Side note: `list` [insertion does not invalidate iterators or references](http://eel.is/c++draft/list#modifiers-2). It's one of the big selling points of `list`. – user4581301 Oct 07 '21 at 00:14
  • 1
    Not being safe and not yielding run time errors are not mutually exclusive. – StoryTeller - Unslander Monica Oct 07 '21 at 00:18
  • 1
    Hazarding a guess, though, I suspect that inserting into `this` could cause an infinite loop. If you insert `begin` to `end` into itself, you'll keep moving `end`. – user4581301 Oct 07 '21 at 00:21

0 Answers0