Implicitly Shared Classes
Status: Inactive
Brought to you by:
manyoso
|
From: Marcus <ma...@my...> - 2003-01-28 08:22:17
|
As I've discussed with Adam, I think that we should change our handling of=
=20
some of the classes in Qt#, particularly the implicitly-shared classes:=20
QBitmap, QBrush, QCursor, QFont, QFontInfo, QFontMetrics, QIconSet, QMap,=20
QPalette, QPen, QPicture, QPixmap, QRegion, QRegExp, QString, QStringList,=
=20
QValueList, and QValueStack.
Of these classes, I've worked most closely with QString, but the other clas=
ses=20
are similar. In each QString instance, one of the fields has type QStringDa=
ta=20
and is named "d". This appears to be a common idiom in C++ -- a d-pointer. =
In=20
any case, the "real" string data of a QString is contained in the d field.=
=20
The QStringData is reference-counted and implicitly-shared. When a QString =
is=20
initially created, its d-pointer is created with the real string data. When=
=20
copying a QString, a new QString is created, but the new QString's d-pointe=
r=20
points to the same data as the origin QString. So the data is shared. QStri=
ng=20
also features copy-on-write so that any QString methods that would alter th=
e=20
d-data cause that data to be copied into a new d-pointer, hence "detached."=
=20
The destructor for QString decrements the reference count. When the referen=
ce=20
count for the QStringData reaches 0, the "real" string data is deleted.
=46rom the Qt# perspective, whenever we create a QString, we are also creat=
ing a=20
new instance of a d-pointer that contains the actual string data. Many=20
methods in Qt# will pass the data to Qt functions. Some Qt functions will=20
retain a copy of the data, using the copy constructor. So the actual data o=
f=20
the string will remain allocated as locate as *any* QString instance needs=
=20
it. The Qt# finalizer ("destructor") for QString can safely delete the=20
QString instance because of this implicit sharing. For it any Qt class stil=
l=20
retains a copy of the QString, the actual string data will be retained as=20
needed. On the other hand, if no copy of the string data is needed, Qt will=
=20
delete the underlying data, thus returning the memory to the feel pool.
|