Reference failure caused by emplace_back in the vector series in practice c ++
Let's talk about the invalid reference caused by emplace_back today.
The code is directly merged:
# Include
# Include
# Include
Using namespace std; int main () {vector
Ivec; ivec. emplace_back (1); ivec. emplace_back (ivec. back (); for (auto it = ivec. begin (); it! = Ivec. end (); ++ it) cout <* it <""; return 0;} // output: 1-572662307
Attempt 1: Do not pass ivec. back () directly to emplace_back ():
# Include
# Include
# Include
Using namespace std; int main () {vector
Ivec; ivec. emplace_back (1); auto & it = ivec. back (); ivec. emplace_back (it); for (auto it = ivec. begin (); it! = Ivec. end (); ++ it) cout <* it <""; return 0;} output: 1-572662307
Try 2: Do not pass reference to emplace_back:
# Include
# Include
# Include
Using namespace std; int main () {vector
Ivec; ivec. emplace_back (1); auto it = ivec. back (); ivec. emplace_back (it); for (auto it = ivec. begin (); it! = Ivec. end (); ++ it) cout <* it <""; return 0;} output: 1 1
We should be able to draw a conclusion at this time, ivec. back () returns a reference, but the reference is invalid, so the output is incorrect. As we mentioned earlier, re-allocating the memory will cause the iterator to become invalid, here, the reference is invalid.
Let's look back at the description of emplace_back:
If a reallocation happens, all iterators, pointers and references related to this container are invalidated.
Otherwise, only the end iterator is invalidated, and all other iterators, pointers and references to elements are guaranteed to keep referring to the same elements they were referring to before the call.
Further.
Try 3: Avoid emplace_back from causing memory reallocation:
# Include
# Include
# Include
Using namespace std; int main () {vector
Ivec; ivec. reserve (4); ivec. emplace_back (1); ivec. emplace_back (ivec. back (); for (auto it = ivec. begin (); it! = Ivec. end (); ++ it) cout <* it <""; return 0;} output: 1 1
However, the problem arises. What if we use push_back instead of emplace_back?
# Include
# Include
# Include
Using namespace std; int main () {vector
Ivec; ivec. push_back (1); ivec. push_back (ivec. back (); ivec. push_back (ivec. back (); ivec. push_back (ivec. back (); for (auto it = ivec. begin (); it! = Ivec. end (); ++ it) cout <* it <""; return 0;} // output: 1 1 1 1
Why does push_back fail?