In "C++ Primer" Section 9.2, Table 9.4, there is an item about seq.assign(b, c)
saying
The iterators b and e must not refer to elements in seq.
However, when I try to use seq.begin()
and seq.end()
to assign back to seq
, it is ok. So I feel confused about this item, or I misunderstand it.
The following code works successfully and outputs 2 3 4
.
#include<iostream>
#include<vector>
int main(){
std::vector<int> b{1, 2, 3, 4};
b.assign(b.begin() + 1, b.end());
std::cout << b[0] << ' ' << b[1] << ' ' << b[2];
return 0;
}
I know assign()
will invalidate iterators into the left-hand container, but what happened in the implementation? Did the destruction happen before the assignment, or after it?
Looking at your code, and reading https://en.cppreference.com/w/cpp/container/vector/assign, it's clear that you are causing undefined behaviour. That means anything might happen - it might just work, it might crash, or it might output incorrect data, or worse things. It's not said that running the same program two times will even produce the same result of undefined behaviour.
So, yes, showing a toy example that things work is worth nothing in terms of correct code, and your code is buggy.
When preconditions on the input of a function are as clearly stated as here, you must not deviate, or you will get unreliable and thus broken behavior.