Value semantics and implicit sharing Back to course

Value semantics and implicit sharing

Qt’s containers and strings are implicitly shared: copying one copies a pointer
and bumps a reference count, and the deep copy happens only when somebody
writes.

QString a = QStringLiteral("shipped");
QString b = a;      // no copy: both point at the same data
b.append('!');      // now b detaches and copies

The cost model is worth stating precisely. For nn copies of which ww are
written to, the deep copies performed are

d=wrather thand=nd = w \quad \text{rather than} \quad d = n

which is why passing QString by value is not the mistake the same
code would be with std::string.

This is a free preview lesson.

Get the full course to unlock the rest of the curriculum.