Skip to content

Instantly share code, notes, and snippets.

@j2doll j2doll/README.md
Last active Sep 14, 2018

Embed
What would you like to do?
Implicit sharing iterator problem of Qt

Implicit sharing iterator problem of Qt

  • Example is based on Qt online help.
// 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
You can’t perform that action at this time.