Implicit sharing

One of the most significant differences between standard library containers and Qt's is the implicit sharing feature. In STL, creating a copy of a container immediately results in a memory allocation and copying the data buffer:

std::vector<int> x { 1, 2, 3};
std::vector<int> y = x; // full copy

If you don't intend to edit the copy, this is essentially a waste of resources, and you want to avoid it. This can be easily done in some cases by providing a reference (const std::vector<int> &) instead of making a copy. However, sometimes it becomes hard to ensure that the reference will be valid long enough, for example, if you want to store it in a class field. An alternative way to solve this task is to wrap a vector in a shared_ptr ...

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.