Reputation: 13
With Qt 5.8.0.
This code runs as I expected.
static const char mydata[] = {
0x1, 0x2, 0x3, 0x4
};
QByteArray ba = QByteArray::fromRawData(mydata, sizeof(mydata));
const char *p = ba.constData();
const char *pp = QByteArray::fromRawData(mydata, sizeof(mydata)).constData();
qDebug("%p %p\n", p, pp);
output
0x40f548 0x40f548
dump
p 0x01 0x02 0x03 0x04
pp 0x01 0x02 0x03 0x04
But, I am struggling to understand what happens with this code after using data() instead of constData().
char *p = ba.data();
char *pp = QByteArray::fromRawData(mydata, sizeof(mydata)).data();
output
0x166941e8 0x166f8e70
dump
p 0x01 0x02 0x03 0x04
pp 0xee 0xfe 0xee 0xfe 0xee 0xfe ... (should be 0x01 0x02 0x03 0x04 ?)
Upvotes: 0
Views: 1146
Reputation: 1484
As explained in Qt documentation, data()
function gives you a deep copy of pointer to QByteArray data so every time that is called, it will gives you another value (different address).
While constData()
gives you a read only pointer to main object so it value doesn't change on every time calling.
For more details you can check here for data() function description, and here for constData() description.
Upvotes: 1