#include <QtCore>
struct test{
int value_a;
unsigned short value_b;
};
int main(int argc, char *argv[])
{
test TA;
TA.value_a = 5;
TA.value_b = 12;
TA.c = "AB";
test TB = TA;
qDebug
() <<
QString("(1)TA.c.constData()=0x%1").
arg((uint
)TA.
c.
constData(),
8,
16,
QChar('0'));
qDebug
() <<
QString("(2)TB.c.constData()=0x%1").
arg((uint
)TB.
c.
constData(),
8,
16,
QChar('0'));
TB.c = "CD";
qDebug
() <<
QString("(3)TA.c.constData()=0x%1").
arg((uint
)TA.
c.
constData(),
8,
16,
QChar('0'));
qDebug
() <<
QString("(4)TB.c.constData()=0x%1").
arg((uint
)TB.
c.
constData(),
8,
16,
QChar('0'));
}
#include <QtCore>
struct test{
int value_a;
unsigned short value_b;
QByteArray c;
};
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QString P;
test TA;
TA.value_a = 5;
TA.value_b = 12;
TA.c = "AB";
test TB = TA;
qDebug() << QString("(1)TA.c.constData()=0x%1").arg((uint)TA.c.constData(), 8, 16, QChar('0'));
qDebug() << QString("(2)TB.c.constData()=0x%1").arg((uint)TB.c.constData(), 8, 16, QChar('0'));
TB.c = "CD";
qDebug() << QString("(3)TA.c.constData()=0x%1").arg((uint)TA.c.constData(), 8, 16, QChar('0'));
qDebug() << QString("(4)TB.c.constData()=0x%1").arg((uint)TB.c.constData(), 8, 16, QChar('0'));
}
To copy to clipboard, switch view to plain text mode
"(1)TA.c.constData()=0x003d5308"
"(2)TB.c.constData()=0x003d5308"
"(3)TA.c.constData()=0x003d5308"
"(4)TB.c.constData()=0x003d5338"
"(1)TA.c.constData()=0x003d5308"
"(2)TB.c.constData()=0x003d5308"
"(3)TA.c.constData()=0x003d5308"
"(4)TB.c.constData()=0x003d5338"
To copy to clipboard, switch view to plain text mode
Qt uses copy-on-write. When you copy QByteArray located in some sturuct, QByteArray::constData() points to the same address (seemingly shallow copy).
However, when you modify (=write to) the (seemingly shallow-copied) QByteArray, it is then copied (detached) from the original one.
COW classes are efficient because copying them involves (basically) copying of internal data pointer (with reference counting); nevertheless from the programmers' point of view, copied data can be modified without affecting the original copy. COW automatically take care of `detaching' (copying internal data when needed), so that you can think of this `seemingly shallow copy' as `efficient deep copy'.
COW is used widely in Qt; so that you can pass QString, QByteArray, QImage, etc. efficiently like below:
QString a=b;
QImage a=b;
To copy to clipboard, switch view to plain text mode
As long as you don't modify, internal data (structure) is shared intelligentlly.
The example below would be ok, because this involves passing shared (reference counting) pointer of internal (bitmap) data from the function to caller.
{
....
return result;
}
QImage createImage()
{
QImage result;
....
return result;
}
To copy to clipboard, switch view to plain text mode
Bookmarks