- Example is based on Qt online help.
Last active
September 14, 2018 02:11
-
-
Save j2doll/bb11c0c8d3d0ddd4066df151fb2dc12a to your computer and use it in GitHub Desktop.
Implicit sharing iterator problem of Qt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// implicit-sharing-iterator-problem-of-qt.cpp | |
// | |
// codehubgist from j2doll | |
#include <QDebug> | |
#include <QtGlobal> | |
#include <QCoreApplication> | |
#include <QVector> | |
#include <cstdio> | |
#include <iostream> | |
#include <vector> | |
#define p1(param1) printf( "[%d] "#param1" = %d\n", __LINE__, param1 ); | |
#define p2(param1, param2) printf( "[%d] "#param1" = %d, "#param2" = %d\n", __LINE__, param1, param2 ); | |
int main(int argc, char *argv[]) | |
{ | |
QCoreApplication a(argc, argv); | |
// implicit sharing iterator problem of Qt | |
{ | |
// STL | |
using namespace std; | |
vector<int> d, e; | |
d.resize(10); | |
vector<int>::iterator j = d.begin(); | |
e = d; // operator= | |
p2( d[0] , e[0] ); // d[0] = 0, e[0] = 0 | |
(*j) = 4; // d[0] is 4. but e[0] is not 4.(it's 0.) | |
p2( d[0] , e[0] ); // d[0] = 4, e[0] = 0 | |
d[0] = 5; | |
e.clear(); | |
int f = *j; | |
p1( f ); // f = 5 | |
} | |
{ | |
// Qt | |
QVector<int> a, b; | |
a.resize(10); | |
QVector<int>::iterator i = a.begin(); | |
b = a; // operator= | |
(*i) = 4; // a[0] and b[0] is four. they are shared data. | |
p2( a[0] , b[0] ); // a[0] = 4, b[0] = 4 | |
a[0] = 5; // container 'a' is detached from shared data. | |
p2( a[0] , b[0] ); // a[0] = 5, b[0] = 4 | |
(*i) = 6; // iterator 'i' only point to container 'a' | |
p2( a[0] , b[0] ); // a[0] = 6, b[0] = 4 | |
b.clear(); | |
int c = *i; | |
p1( c ); // c = 6 | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment