Qt文档阅读笔记-隐式共享(Implicit Sharing)深入研究(理论及实例)
Qt里面很多C++類都是采用隱式共享最大限度的提高資源利用率以及最新復(fù)制的原則。隱式共享數(shù)據(jù)作為參數(shù)時,不僅安全而且高效,因為傳的是一個指針并且只有要修改這個數(shù)據(jù)時才會去拷貝,這里有個專業(yè)詞匯copy-on-write在Qt官方提供的ppt中經(jīng)常會出現(xiàn)這個詞,說的就是隱式共享。
?
共享類(這個應(yīng)該是指value?type的類,學(xué)過Qt的都知道,Qt類可以分為兩類,一個是identity?type和value?type)由一個共享數(shù)據(jù)塊及指向這個塊的計數(shù)器組成。
當(dāng)共享對象被創(chuàng)建,這個塊的計數(shù)器的值會被設(shè)置為1,并且當(dāng)有新的對象指向共享數(shù)據(jù)庫,那么他的計數(shù)器就會+1,當(dāng)對象不指向這個內(nèi)存塊時,計數(shù)器會減少,當(dāng)計數(shù)器為0時,這個共享塊將會被刪除。
當(dāng)要對共享數(shù)據(jù)進行處理時,Qt有2種方式進行拷貝,也就是常說的深拷貝與淺拷貝。這里不再解釋這2個拷貝了,這個隱式共享就和淺拷貝差不多,只不過是多了給增加了個引用計數(shù)器。
=這個操作一般是淺拷貝。
?
Qt的容器iterator和STL的不同,主要也是圍繞隱式共享。如下代碼:
#include <QVector> #include <QDebug>int main(int argc, char *argv[]) {QVector<int> a, b;a.resize(100000);QVector<int>::iterator i = a.begin();b = a;*i = 4;a[0] = 5;b.clear();int j = *i;qDebug() << "OVER";}下面最關(guān)鍵的來了,演示下上面所說的理論
這里可以看到當(dāng)*i?=?4還沒執(zhí)行的時候a中RefCount為2,也就是a,b都引用到了這個隱式內(nèi)存中,所以為2。而這個i是直接指向了目前a最開始的那個內(nèi)存。
下面看下一張圖:
這里可以看到*i=4改變后,因為改變的是共享內(nèi)存,所有a和b里面的數(shù)據(jù)都被改了。
最關(guān)鍵的地方來了,大家要注意,Qt最強大的機制之一copy-on-write來了。
這里a[0]=5,寫及拷貝。a重新進行構(gòu)造,現(xiàn)在RefCount又變成1了。
這個程序想表示的就是這個。也就是Qt很重要的運行機制。
還有給要提的就是這個i。
當(dāng)b被clear后這個i就有問題,int?j?=?i;這種操作很不安全。
?
當(dāng)開發(fā)者需要寫自己的隱式共享類時,使用QSharedData和QSharedDataPointer類。
?
當(dāng)需要改變數(shù)據(jù)的時候,數(shù)據(jù)將會從隱式共享分離。
如下面這個QPen類,內(nèi)部是這樣處理的
void QPen::setStyle(Qt::PenStyle style){detach(); // detach from common datad->style = style; // set the style member}void QPen::detach(){if (d->ref != 1) {... // perform a deep copy}}當(dāng)setStyle被調(diào)用后,這個set為設(shè)置,所以改變了,就會調(diào)用detach(),當(dāng)d-ref不為1時,就會把所有數(shù)據(jù)拷貝一份。
?
下面是一些隱式共享的類,這里要記住,QTL的容器如果用STL風(fēng)格去操作,需要考慮下隱式共享方面的問題。
| QDebug | Output?stream?for?debugging?information |
| QDir | Access?to?directory?structures?and?their?contents |
| QFileInfo | System-independent?file?information |
| QProcessEnvironment | Holds?the?environment?variables?that?can?be?passed?to?a?program |
| QStorageInfo | Provides?information?about?currently?mounted?storage?and?drives |
| QUrl | Convenient?interface?for?working?with?URLs |
| QUrlQuery | Way?to?manipulate?a?key-value?pairs?in?a?URL's?query |
| QPersistentModelIndex | Used?to?locate?data?in?a?data?model |
| QJsonArray | Encapsulates?a?JSON?array |
| QJsonDocument | Way?to?read?and?write?JSON?documents |
| QJsonParseError | Used?to?report?errors?during?JSON?parsing |
| QJsonObject | Encapsulates?a?JSON?object |
| QJsonValue | Encapsulates?a?value?in?JSON |
| QVariant | Acts?like?a?union?for?the?most?common?Qt?data?types |
| QMimeType | Describes?types?of?file?or?data,?represented?by?a?MIME?type?string |
| QBitArray | Array?of?bits |
| QByteArray | Array?of?bytes |
| QByteArrayList | List?of?byte?arrays |
| QCache | Template?class?that?provides?a?cache |
| QCollator | Compares?strings?according?to?a?localized?collation?algorithm |
| QCollatorSortKey | Can?be?used?to?speed?up?string?collation |
| QCommandLineOption | Defines?a?possible?command-line?option |
| QContiguousCache | Template?class?that?provides?a?contiguous?cache |
| QDateTime | Date?and?time?functions |
| QHash | Template?class?that?provides?a?hash-table-based?dictionary |
| QMultiHash | Convenience?QHash?subclass?that?provides?multi-valued?hashes |
| QLinkedList | Template?class?that?provides?linked?lists |
| QList | Template?class?that?provides?lists |
| QLocale | Converts?between?numbers?and?their?string?representations?in?various?languages |
| QMap | Template?class?that?provides?a?red-black-tree-based?dictionary |
| QMultiMap | Convenience?QMap?subclass?that?provides?multi-valued?maps |
| QQueue | Generic?container?that?provides?a?queue |
| QRegExp | Pattern?matching?using?regular?expressions |
| QRegularExpression | Pattern?matching?using?regular?expressions |
| QRegularExpressionMatch | The?results?of?matching?a?QRegularExpression?against?a?string |
| QRegularExpressionMatchIterator | Iterator?on?the?results?of?a?global?match?of?a?QRegularExpression?object?against?a?string |
| QSet | Template?class?that?provides?a?hash-table-based?set |
| QStack | Template?class?that?provides?a?stack |
| QString | Unicode?character?string |
| QStringList | List?of?strings |
| QTextBoundaryFinder | Way?of?finding?Unicode?text?boundaries?in?a?string |
| QVector | Template?class?that?provides?a?dynamic?array |
| QDBusPendingCall | Refers?to?one?pending?asynchronous?call |
| QDBusUnixFileDescriptor | Holds?one?Unix?file?descriptor |
| QBitmap | Monochrome?(1-bit?depth)?pixmaps |
| QIcon | Scalable?icons?in?different?modes?and?states |
| QImage | Hardware-independent?image?representation?that?allows?direct?access?to?the?pixel?data,?and?can?be?used?as?a?paint?device |
| QPicture | Paint?device?that?records?and?replays?QPainter?commands |
| QPixmap | Off-screen?image?representation?that?can?be?used?as?a?paint?device |
| QCursor | Mouse?cursor?with?an?arbitrary?shape |
| QKeySequence | Encapsulates?a?key?sequence?as?used?by?shortcuts |
| QPalette | Contains?color?groups?for?each?widget?state |
| QOpenGLDebugMessage | Wraps?an?OpenGL?debug?message |
| QBrush | Defines?the?fill?pattern?of?shapes?drawn?by?QPainter |
| QGradient | Used?in?combination?with?QBrush?to?specify?gradient?fills |
| QPainterPath | Container?for?painting?operations,?enabling?graphical?shapes?to?be?constructed?and?reused |
| QPen | Defines?how?a?QPainter?should?draw?lines?and?outlines?of?shapes |
| QPolygon | Vector?of?points?using?integer?precision |
| QPolygonF | Vector?of?points?using?floating?point?precision |
| QRegion | Specifies?a?clip?region?for?a?painter |
| QFont | Specifies?a?font?used?for?drawing?text |
| QFontInfo | General?information?about?fonts |
| QFontMetrics | Font?metrics?information |
| QFontMetricsF | Font?metrics?information |
| QGlyphRun | Direct?access?to?the?internal?glyphs?in?a?font |
| QRawFont | Access?to?a?single?physical?instance?of?a?font |
| QStaticText | Enables?optimized?drawing?of?text?when?the?text?and?its?layout?is?updated?rarely |
| QTextCursor | Offers?an?API?to?access?and?modify?QTextDocuments |
| QTextDocumentFragment | Represents?a?piece?of?formatted?text?from?a?QTextDocument |
| QTextBlockFormat | Formatting?information?for?blocks?of?text?in?a?QTextDocument |
| QTextCharFormat | Formatting?information?for?characters?in?a?QTextDocument |
| QTextFormat | Formatting?information?for?a?QTextDocument |
| QTextFrameFormat | Formatting?information?for?frames?in?a?QTextDocument |
| QTextImageFormat | Formatting?information?for?images?in?a?QTextDocument |
| QTextListFormat | Formatting?information?for?lists?in?a?QTextDocument |
| QTextTableCellFormat | Formatting?information?for?table?cells?in?a?QTextDocument |
| QTextTableFormat | Formatting?information?for?tables?in?a?QTextDocument |
| QNetworkCacheMetaData | Cache?information |
| QHttpPart | Holds?a?body?part?to?be?used?inside?a?HTTP?multipart?MIME?message |
| QNetworkCookie | Holds?one?network?cookie |
| QNetworkRequest | Holds?a?request?to?be?sent?with?QNetworkAccessManager |
| QNetworkConfiguration | Abstraction?of?one?or?more?access?point?configurations |
| QDnsDomainNameRecord | Stores?information?about?a?domain?name?record |
| QDnsHostAddressRecord | Stores?information?about?a?host?address?record |
| QDnsMailExchangeRecord | Stores?information?about?a?DNS?MX?record |
| QDnsServiceRecord | Stores?information?about?a?DNS?SRV?record |
| QDnsTextRecord | Stores?information?about?a?DNS?TXT?record |
| QNetworkAddressEntry | Stores?one?IP?address?supported?by?a?network?interface,?along?with?its?associated?netmask?and?broadcast?address |
| QNetworkInterface | Listing?of?the?host's?IP?addresses?and?network?interfaces |
| QNetworkProxy | Network?layer?proxy |
| QNetworkProxyQuery | Used?to?query?the?proxy?settings?for?a?socket |
| QSslCertificate | Convenient?API?for?an?X509?certificate |
| QSslCertificateExtension | API?for?accessing?the?extensions?of?an?X509?certificate |
| QSslCipher | Represents?an?SSL?cryptographic?cipher |
| QSslConfiguration | Holds?the?configuration?and?state?of?an?SSL?connection |
| QSslDiffieHellmanParameters | Interface?for?Diffie-Hellman?parameters?for?servers |
| QSslError | SSL?error |
| QSslKey | Interface?for?private?and?public?keys |
| QSslPreSharedKeyAuthenticator | Authentication?data?for?pre?shared?keys?(PSK)?ciphersuites |
總結(jié)
以上是生活随笔為你收集整理的Qt文档阅读笔记-隐式共享(Implicit Sharing)深入研究(理论及实例)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: canvas笔记-文本(fillText
- 下一篇: Java工作笔记-JPA中Reposit