Qt Implicit sharing Basic Concept


Example

Several Qt Objects and Containers use a concept calles implicit sharing, which can also be refered to as copy-on-write.

Implicit sharing means that the classes who use this concept share the same data on initialization.

One of these classes to use the concept is QString.

QString s1("Hello World");

One QString initialization

This is a simplified model of a QString. Internally it has a memory block, with the actual string data and and a reference counter.

QString s2 = s1;

copy QString

If we now copy this QString both objects will internally point to the same content, thus avoiding unnecessary copy operations. Note how the reference count also got upped. So in case the first string gets deleted the shared-data still knows it is referenced by another QString.

s2 += " and all the other Worlds!"

Copy on Write

Now when the QString is actually modified the object "detaches" itself from the memory block, copying it's content and modifies the content.