Game Programming using Qt 5 Beginner's Guide - Second Edition
by Pavel Strakhov, Witold Wysota, Lorenz Haas
Unnecessary allocation
The next question is what actions on the object trigger the actual allocation of a new buffer? Obviously, x[0] = 42 will trigger an allocation because the vector needs a buffer to write the new data to. However, int i = x[0] will also trigger an allocation if x is not declared as a const value or reference. That happens because in C++ this code triggers the non-const overload of operator[] if it's available, even though it's not necessary in this case. The vector doesn't know whether the requested item will or will not be changed, so it has to assume that it will be, and it triggers an allocation before returning a reference to the item in the new buffer.
The same issue takes effect when using other methods that have ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access