What just happened?

As we copied the x vector to y, the state of two vectors became shared and the original buffer was available to both of them. However, when we modified x using operator[], it became detached, that is, a new buffer was allocated for it, and y retained the original buffer. The x0 pointer continues to point at the original buffer, which is now only available to y. If you remove the QVector<int> y = x; line, the output will change to the expected 42. The general rule is that you should avoid storing pointers or references to the object's content while it's changed or shared with another object.

Get Game Programming using Qt 5 Beginner's Guide - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.