Viadeo Twitter Google Bookmarks ! Facebook Digg del.icio.us MySpace Yahoo MyWeb Blinklist Netvouz Reddit Simpy StumbleUpon Bookmarks Windows Live Favorites 
Logo Documentation Qt ·  Page d'accueil  ·  Tous les espaces de nom  ·  Toutes les classes  ·  Classes principales  ·  Annotées  ·  Classes groupées  ·  Modules  ·  Fonctions  · 

Implicitly Shared Classes

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 takes place behind the scenes; the programmer does not need to worry about it. Even in multithreaded applications, implicit sharing takes place, as explained in Threads and Implicit Sharing.

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 total control of its internal data. In any member functions that modify its data, it automatically detaches before modifying the data.

The QPen class, 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, p1 and p2 share data until QPainter::begin() is called for p2, because painting a pixmap will modify it.

Warning: Do not copy an implicitly shared container (QMap, QVector, etc.) while you are iterating over it using an non-const STL-style iterator.

QBitArrayArray of bits
QBitmapMonochrome (1-bit depth) pixmaps
QBrushDefines the fill pattern of shapes drawn by QPainter
QByteArrayArray of bytes
QCacheTemplate class that provides a cache
QCursorMouse cursor with an arbitrary shape
QDirAccess to directory structures and their contents
QFileInfoSystem-independent file information
QFontSpecifies a font used for drawing text
QFontInfoGeneral information about fonts
QFontMetricsFont metrics information
QFontMetricsFFont metrics information
QGLColormapUsed for installing custom colormaps into QGLWidgets
QGradientUsed in combination with QBrush to specify gradient fills
QHashTemplate class that provides a hash-table-based dictionary
QIconScalable icons in different modes and states
QImageHardware-independent image representation that allows direct access to the pixel data, and can be used as a paint device
QKeySequenceEncapsulates a key sequence as used by shortcuts
QLinkedListTemplate class that provides linked lists
QListTemplate class that provides lists
QLocaleConverts between numbers and their string representations in various languages
QMapTemplate class that provides a skip-list-based dictionary
QMultiHashConvenience QHash subclass that provides multi-valued hashes
QMultiMapConvenience QMap subclass that provides multi-valued maps
QPainterPathContainer for painting operations, enabling graphical shapes to be constructed and reused
QPaletteContains color groups for each widget state
QPenDefines how a QPainter should draw lines and outlines of shapes
QPicturePaint device that records and replays QPainter commands
QPixmapOff-screen image representation that can be used as a paint device
QPolygonVector of points using integer precision
QPolygonFVector of points using floating point precision
QQueueGeneric container that provides a queue
QRegExpPattern matching using regular expressions
QRegionSpecifies a clip region for a painter
QSetTemplate class that provides a hash-table-based set
QSqlFieldManipulates the fields in SQL database tables and views
QSqlQueryMeans of executing and manipulating SQL statements
QSqlRecordEncapsulates a database record
QStackTemplate class that provides a stack
QStringUnicode character string
QStringListList of strings
QTextBoundaryFinderWay of finding Unicode text boundaries in a string
QTextCursorOffers an API to access and modify QTextDocuments
QTextDocumentFragmentRepresents a piece of formatted text from a QTextDocument
QTextFormatFormatting information for a QTextDocument
QUrlConvenient interface for working with URLs
QVariantActs like a union for the most common Qt data types
QVectorTemplate class that provides a dynamic array
QX11InfoInformation about the X display configuration

Publicité

Best Of

Actualités les plus lues

Semaine
Mois
Année
  1. « Quelque chose ne va vraiment pas avec les développeurs "modernes" », un développeur à "l'ancienne" critique la multiplication des bibliothèques 94
  2. Apercevoir la troisième dimension ou l'utilisation multithreadée d'OpenGL dans Qt, un article des Qt Quarterly traduit par Guillaume Belz 0
  3. Les développeurs ignorent-ils trop les failles découvertes dans leur code ? Prenez-vous en compte les remarques des autres ? 17
  4. Pourquoi les programmeurs sont-ils moins payés que les gestionnaires de programmes ? Manquent-ils de pouvoir de négociation ? 42
  5. Quelles nouveautés de C++11 Visual C++ doit-il rapidement intégrer ? Donnez-nous votre avis 10
  6. Adieu qmake, bienvenue qbs : Qt Building Suite, un outil déclaratif et extensible pour la compilation de projets Qt 17
  7. 2017 : un quinquennat pour une nouvelle version du C++ ? Possible, selon Herb Sutter 7
Page suivante

Le blog Digia au hasard

Logo

Créer des applications avec un style Metro avec Qt, exemples en QML et C++, un article de Digia Qt traduit par Thibaut Cuvelier

Le blog Digia est l'endroit privilégié pour la communication sur l'édition commerciale de Qt, où des réponses publiques sont apportées aux questions les plus posées au support. Lire l'article.

Communauté

Ressources

Liens utiles

Contact

  • Vous souhaitez rejoindre la rédaction ou proposer un tutoriel, une traduction, une question... ? Postez dans le forum Contribuez ou contactez-nous par MP ou par email (voir en bas de page).

Qt dans le magazine

Cette page est une traduction d'une page de la documentation de Qt, écrite par Nokia Corporation and/or its subsidiary(-ies). Les éventuels problèmes résultant d'une mauvaise traduction ne sont pas imputables à Nokia. Qt 4.4
Copyright © 2012 Developpez LLC. Tous droits réservés Developpez LLC. Aucune reproduction, même partielle, ne peut être faite de ce site et de l'ensemble de son contenu : textes, documents et images sans l'autorisation expresse de Developpez LLC. Sinon, vous encourez selon la loi jusqu'à 3 ans de prison et jusqu'à 300 000 E de dommages et intérêts. Cette page est déposée à la SACD.
Vous avez déniché une erreur ? Un bug ? Une redirection cassée ? Ou tout autre problème, quel qu'il soit ? Ou bien vous désirez participer à ce projet de traduction ? N'hésitez pas à nous contacter ou par MP !
 
 
 
 
Partenaires

Hébergement Web