Implicit Sharing¶
Many C++ classes in Qt use implicit data sharing to maximize resource usage and minimize copying. Implicitly shared classes are both safe and efficient when passed as arguments, because only a pointer to the data is passed around, and the data is copied only if and when a function writes to it, i.e., copy-on-write .
Overview¶
A shared class consists of a pointer to a shared data block that contains a reference count and the data.
When a shared object is created, it sets the reference count to 1. The reference count is incremented whenever a new object references the shared data, and decremented when the object dereferences the shared data. The shared data is deleted when the reference count becomes zero.
When dealing with shared objects, there are two ways of copying an object. We usually speak about deep and shallow copies. A deep copy implies duplicating an object. A shallow copy is a reference copy, i.e. just a pointer to a shared data block. Making a deep copy can be expensive in terms of memory and CPU. Making a shallow copy is very fast, because it only involves setting a pointer and incrementing the reference count.
Object assignment (with operator=()) for implicitly shared objects is implemented using shallow copies.
The benefit of sharing is that a program does not need to duplicate data unnecessarily, which results in lower memory use and less copying of data. Objects can easily be assigned, sent as function arguments, and returned from functions.
Implicit sharing mostly takes place behind the scenes; the programmer rarely needs to worry about it. However, Qt’s container iterators have different behavior than those from the STL. Read Implicit sharing iterator problem .
In multithreaded applications, implicit sharing takes place, as explained in Threads and Implicitly Shared Classes.
When implementing your own implicitly shared classes, use the
QSharedDataandQSharedDataPointerclasses.
Implicit Sharing in Detail¶
Implicit sharing automatically detaches the object from a shared block if the object is about to change and the reference count is greater than one. (This is often called copy-on-write or value semantics .)
An implicitly shared class has control of its internal data. In any member functions that modify its data, it automatically detaches before modifying the data. Notice, however, the special case with container iterators; see Implicit sharing iterator problem .
The
QPenclass, which uses implicit sharing, detaches from the shared data in all member functions that change the internal data.Code fragment:
void QPen::setStyle(Qt::PenStyle style) { detach(); // detach from common data d->style = style; // set the style member } void QPen::detach() { if (d->ref != 1) { ... // perform a deep copy } }
List of Classes¶
The classes listed below automatically detach from common data if an object is about to be changed. The programmer will not even notice that the objects are shared. Thus you should treat separate instances of them as separate objects. They will always behave as separate objects but with the added benefit of sharing data whenever possible. For this reason, you can pass instances of these classes as arguments to functions by value without concern for the copying overhead.
Example:
QPixmap p1, p2; p1.load("image.bmp"); p2 = p1; // p1 and p2 share data QPainter paint; paint.begin(&p2); // cuts p2 loose from p1 paint.drawText(0,50, "Hi"); paint.end();In this example,
p1andp2share data untilbegin()is called forp2, because painting a pixmap will modify it.Warning
Be careful with copying an implicitly shared container (
QMap,QVector, etc.) while you use STL-style iterator . See Implicit sharing iterator problem .
QDebugThe QDebug class provides an output stream for debugging information.
PySide2.QtCore.QDirThe QDir class provides access to directory structures and their contents.
PySide2.QtCore.QFileInfoThe QFileInfo class provides system-independent file information.
PySide2.QtCore.QProcessEnvironmentThe QProcessEnvironment class holds the environment variables that can be passed to a program.
PySide2.QtCore.QStorageInfoProvides information about currently mounted storage and drives.
PySide2.QtCore.QUrlThe QUrl class provides a convenient interface for working with URLs.
PySide2.QtCore.QUrlQueryThe QUrlQuery class provides a way to manipulate a key-value pairs in a URL’s query.
PySide2.QtCore.QPersistentModelIndexThe QPersistentModelIndex class is used to locate data in a data model.
PySide2.QtCore.QVariantThe QVariant class acts like a union for the most common Qt data types.
PySide2.QtCore.QMimeTypeThe QMimeType class describes types of file or data, represented by a MIME type string.
PySide2.QtCore.QJsonArrayThe QJsonArray class encapsulates a JSON array.
PySide2.QtCore.QJsonDocumentThe QJsonDocument class provides a way to read and write JSON documents.
PySide2.QtCore.QJsonObjectThe QJsonObject class encapsulates a JSON object.
PySide2.QtCore.QJsonParseErrorThe QJsonParseError class is used to report errors during JSON parsing.
PySide2.QtCore.QJsonValueThe QJsonValue class encapsulates a value in JSON.
PySide2.QtCore.QByteArrayThe QByteArray class provides an array of bytes.
QByteArrayListThe QByteArrayList class provides a list of byte arrays.
PySide2.QtCore.QCollatorThe QCollator class compares strings according to a localized collation algorithm.
PySide2.QtCore.QCollatorSortKeyThe QCollatorSortKey class can be used to speed up string collation.
PySide2.QtCore.QLocaleThe QLocale class converts between numbers and their string representations in various languages.
PySide2.QtCore.QRegExpThe QRegExp class provides pattern matching using regular expressions.
PySide2.QtCore.QRegularExpressionThe QRegularExpression class provides pattern matching using regular expressions.
PySide2.QtCore.QRegularExpressionMatchThe QRegularExpressionMatch class provides the results of a matching a QRegularExpression against a string.
PySide2.QtCore.QRegularExpressionMatchIteratorThe QRegularExpressionMatchIterator class provides an iterator on the results of a global match of a QRegularExpression object against a string.
PySide2.QtCore.QStringThe QString class provides a Unicode character string.
The QStringBuilder class is a template class that provides a facility to build up QStrings and QByteArrays from smaller chunks.
PySide2.QtCore.QStringListThe QStringList class provides a list of strings.
PySide2.QtCore.QTextBoundaryFinderThe QTextBoundaryFinder class provides a way of finding Unicode text boundaries in a string.
PySide2.QtCore.QDateTimeThe QDateTime class provides date and time functions.
PySide2.QtCore.QBitArrayThe QBitArray class provides an array of bits.
QCacheThe QCache class is a template class that provides a cache.
PySide2.QtCore.QCommandLineOptionThe QCommandLineOption class defines a possible command-line option.
QContiguousCacheThe QContiguousCache class is a template class that provides a contiguous cache.
QHashThe QHash class is a template class that provides a hash-table-based dictionary.
QMultiHashThe QMultiHash class is a convenience QHash subclass that provides multi-valued hashes.
QLinkedListThe QLinkedList class is a template class that provides linked lists.
QListThe QList class is a template class that provides lists.
QMapThe QMap class is a template class that provides a red-black-tree-based dictionary.
QMultiMapThe QMultiMap class is a convenience QMap subclass that provides multi-valued maps.
QQueueThe QQueue class is a generic container that provides a queue.
QSetThe QSet class is a template class that provides a hash-table-based set.
QStackThe QStack class is a template class that provides a stack.
QVectorThe QVector class is a template class that provides a dynamic array.
PySide2.QtGui.QBitmapThe QBitmap class provides monochrome (1-bit depth) pixmaps.
PySide2.QtGui.QIconThe QIcon class provides scalable icons in different modes and states.
PySide2.QtGui.QImageThe QImage class provides a hardware-independent image representation that allows direct access to the pixel data, and can be used as a paint device.
PySide2.QtGui.QPictureThe QPicture class is a paint device that records and replays QPainter commands.
PySide2.QtGui.QPixmapThe QPixmap class is an off-screen image representation that can be used as a paint device.
PySide2.QtGui.QCursorThe QCursor class provides a mouse cursor with an arbitrary shape.
PySide2.QtGui.QKeySequenceThe QKeySequence class encapsulates a key sequence as used by shortcuts.
PySide2.QtGui.QPaletteThe QPalette class contains color groups for each widget state.
PySide2.QtGui.QOpenGLDebugMessageThe QOpenGLDebugMessage class wraps an OpenGL debug message.
PySide2.QtGui.QBrushThe QBrush class defines the fill pattern of shapes drawn by QPainter.
PySide2.QtGui.QGradientThe QGradient class is used in combination with QBrush to specify gradient fills.
PySide2.QtGui.QPainterPathThe QPainterPath class provides a container for painting operations, enabling graphical shapes to be constructed and reused.
PySide2.QtGui.QPenThe QPen class defines how a QPainter should draw lines and outlines of shapes.
PySide2.QtGui.QPolygonThe QPolygon class provides a vector of points using integer precision.
PySide2.QtGui.QPolygonFThe QPolygonF class provides a vector of points using floating point precision.
PySide2.QtGui.QRegionThe QRegion class specifies a clip region for a painter.
PySide2.QtGui.QFontThe QFont class specifies a query for a font used for drawing text.
PySide2.QtGui.QFontInfoThe QFontInfo class provides general information about fonts.
PySide2.QtGui.QFontMetricsThe QFontMetrics class provides font metrics information.
PySide2.QtGui.QFontMetricsFThe QFontMetricsF class provides font metrics information.
QGlyphRunThe QGlyphRun class provides direct access to the internal glyphs in a font.
PySide2.QtGui.QRawFontThe QRawFont class provides access to a single physical instance of a font.
PySide2.QtGui.QStaticTextThe QStaticText class enables optimized drawing of text when the text and its layout is updated rarely.
PySide2.QtGui.QTextCursorThe QTextCursor class offers an API to access and modify QTextDocuments.
PySide2.QtGui.QTextDocumentFragmentThe QTextDocumentFragment class represents a piece of formatted text from a QTextDocument.
PySide2.QtGui.QTextFormatThe QTextFormat class provides formatting information for a QTextDocument.
PySide2.QtGui.QTextCharFormatThe QTextCharFormat class provides formatting information for characters in a QTextDocument.
PySide2.QtGui.QTextBlockFormatThe QTextBlockFormat class provides formatting information for blocks of text in a QTextDocument.
PySide2.QtGui.QTextListFormatThe QTextListFormat class provides formatting information for lists in a QTextDocument.
PySide2.QtGui.QTextFrameFormatThe QTextFrameFormat class provides formatting information for frames in a QTextDocument.
PySide2.QtGui.QTextTableFormatThe QTextTableFormat class provides formatting information for tables in a QTextDocument.
PySide2.QtGui.QTextImageFormatThe QTextImageFormat class provides formatting information for images in a QTextDocument.
PySide2.QtGui.QTextTableCellFormatThe QTextTableCellFormat class provides formatting information for table cells in a QTextDocument.
PySide2.QtNetwork.QNetworkCacheMetaDataThe QNetworkCacheMetaData class provides cache information.
QHttp2ConfigurationThe QHttp2Configuration class controls HTTP/2 parameters and settings.
PySide2.QtNetwork.QHttpPartThe QHttpPart class holds a body part to be used inside a HTTP multipart MIME message.
PySide2.QtNetwork.QNetworkCookieThe QNetworkCookie class holds one network cookie.
PySide2.QtNetwork.QNetworkRequestThe QNetworkRequest class holds a request to be sent with QNetworkAccessManager.
PySide2.QtNetwork.QNetworkConfigurationThe QNetworkConfiguration class provides an abstraction of one or more access point configurations.
PySide2.QtNetwork.QDnsDomainNameRecordThe QDnsDomainNameRecord class stores information about a domain name record.
PySide2.QtNetwork.QDnsHostAddressRecordThe QDnsHostAddressRecord class stores information about a host address record.
PySide2.QtNetwork.QDnsMailExchangeRecordThe QDnsMailExchangeRecord class stores information about a DNS MX record.
PySide2.QtNetwork.QDnsServiceRecordThe QDnsServiceRecord class stores information about a DNS SRV record.
PySide2.QtNetwork.QDnsTextRecordThe QDnsTextRecord class stores information about a DNS TXT record.
PySide2.QtNetwork.QHostAddressThe QHostAddress class provides an IP address.
PySide2.QtNetwork.QNetworkAddressEntryThe QNetworkAddressEntry class stores one IP address supported by a network interface, along with its associated netmask and broadcast address.
PySide2.QtNetwork.QNetworkInterfaceThe QNetworkInterface class provides a listing of the host’s IP addresses and network interfaces.
PySide2.QtNetwork.QNetworkProxyThe QNetworkProxy class provides a network layer proxy.
PySide2.QtNetwork.QNetworkProxyQueryThe QNetworkProxyQuery class is used to query the proxy settings for a socket.
PySide2.QtNetwork.QSslCertificateThe QSslCertificate class provides a convenient API for an X509 certificate.
PySide2.QtNetwork.QSslCertificateExtensionThe QSslCertificateExtension class provides an API for accessing the extensions of an X509 certificate.
PySide2.QtNetwork.QSslCipherThe QSslCipher class represents an SSL cryptographic cipher.
PySide2.QtNetwork.QSslConfigurationThe QSslConfiguration class holds the configuration and state of an SSL connection.
PySide2.QtNetwork.QSslDiffieHellmanParametersThe QSslDiffieHellmanParameters class provides an interface for Diffie-Hellman parameters for servers.
PySide2.QtNetwork.QSslErrorThe QSslError class provides an SSL error.
PySide2.QtNetwork.QSslKeyThe QSslKey class provides an interface for private and public keys.
PySide2.QtNetwork.QSslPreSharedKeyAuthenticatorThe QSslPreSharedKeyAuthenticator class provides authentication data for pre shared keys (PSK) ciphersuites.
PySide2.QtOpenGL.QGLColormapThe QGLColormap class is used for installing custom colormaps into a QGLWidget.
PySide2.QtSql.QSqlFieldThe QSqlField class manipulates the fields in SQL database tables and views.
PySide2.QtSql.QSqlQueryThe QSqlQuery class provides a means of executing and manipulating SQL statements.
PySide2.QtSql.QSqlRecordThe QSqlRecord class encapsulates a database record.
© 2022 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.