[Qt-interest] memory control in QImage bits() function

Oliver.Knoll at comit.ch Oliver.Knoll at comit.ch
Wed Mar 17 14:18:47 CET 2010


Mehmet Kaplan wrote on Wednesday, March 17, 2010 1:15 PM:

> ...
> in definition of bits() function it is written that:
> "Note that QImage uses implicit data sharing. This function performs
> a deep copy of the shared pixel data, thus ensuring that this QImage
> is the only one using the current return value."  

What this means: QImage uses implicit sharing *between this instance and other instances of QImage*! So when you call bits() a deep copy is enforced so that *this QImage* (and *not* the caller of bits()) has now a unique copy of its data. So no, you *don't* get a copy of the pixel data with bits(). You get *direct access* to the pixel data, just as the Qt docs sais ("This is equivalent to scanLine(0).").

For instance (pseudo-code):

QImage a, b;
a = QImage(640, 480); // allocate image of size 640 x 480;
b = a; // IMPLICIT sharing! No pixel data is copied yet.
uchar *bits = a.bits(); // NOW a deep copy is enforced between a and b (and NOT "into bits")

// image 'a' ONLY is modified (and YES, it IS modified - b however has now its own pixel data copy and is NOT modified)
bits[0] = 0;
bits[1] = 1;
....

> But after a statement like this
> for(int i=0;i<100000;i++)
> 	newData [i]=0;
> 
> original QImage is also changes (first few lines become black because
> of zero value). 

By design and totally on purpose, see above. 

You might want to get a better understanding of what "implicit sharing" is all about here: http://doc.trolltech.com/4.6/implicit-sharing.html

Cheers, Oliver
-- 
Oliver Knoll
Dipl. Informatik-Ing. ETH
COMIT AG - ++41 79 520 95 22



More information about the Qt-interest-old mailing list