COW is used. Shallow copy takes place when copy construct a new object. Deep copy when writing takes place.
Qpen.h
void QPen::setWidth(int width)
{
if (width < 0)
qWarning("QPen::setWidth: Setting a pen width with a negative value is not defined");
if ((qreal)width == d->width)
return;
detach(); //COW
d->width = width;
}
//detach is used to deep copy a object when no deep copy takes place before.
void QPen::detach()
{
if (d->ref == 1)
return;
QPenData *x = new QPenData(*static_cast<QPenData *>(d));
if (!d->ref.deref())
delete d;
x->ref = 1;
d = x;
}
//Shallow copy when assigning
QPen &QPen::operator=(const QPen &p)
{
qAtomicAssign(d, p.d);
return *this;
}
template <typename T>
inline void qAtomicAssign(T *&d, T *x)
{
if (d == x)
return;
x->ref.ref();
if (!d->ref.deref())
delete d;
d = x;
}
template <typename T>
inline void qAtomicDetach(T *&d)
{
if (d->ref == 1)
return;
T *x = d;
d = new T(*d);
if (!x->ref.deref())
delete x;
}
Explicitly sharing:
Qshareddata.h
inline QExplicitlySharedDataPointer<T> & operator=(const QExplicitlySharedDataPointer<T> &o) {
if (o.d != d) {
if (o.d)
o.d->ref.ref();
T *old = d;
d = o.d;
if (old && !old->ref.deref())
delete old;
}
return *this;
}