PDA

View Full Version : Implicit sharing and pointers



Luc4
16th June 2010, 00:40
Hi! I have a doubt on implicit sharing. If I have a pointer to a QImage named pImage, and I create a QImage by creating a shallow copy this way:


QImage image(*pImage);

when image will be destroyed, because the ref counter has reached zero, will the space allocated for pImage be deallocated? Or will I have that data pImage refers to (so an entire QImage) will remain? Sorry for the stupid question but I really can't sort myself out.
Thanks!

Zlatomir
16th June 2010, 01:39
The first "clue" is that QImage doesn't have a constructor that takes a QImage* as a parameter.

And second thing that a want to add is: don't do that, if you need to copy, than copy the object not just the pointer.

The other way might look "ok" if you perform just some "small tests", because if you delete the first pointer and access the memory from the second (copy) pointer, the program might work "ok" a couple of times, because the memory isn't zero-ed out, it's just marked as un-allocated and the object remains until some other parts of your program write that memory and this is the "easy" way for you to get some hard to debug "Segmentation Fault" errors at run-time.

wysota
16th June 2010, 01:44
will the space allocated for pImage be deallocated?
One is contradictory with the other. Refcount will not go down to zero until you explicitely delete pImage because pImage will be referencing the data.

Luc4
16th June 2010, 09:14
And second thing that a want to add is: don't do that, if you need to copy, than copy the object not just the pointer.

Copy? I suppose this is not a good solution both in terms of memory and of computational performance (I'm working on a slow device).


One is contradictory with the other. Refcount will not go down to zero until you explicitely delete pImage because pImage will be referencing the data.

mmh... and what about I create the new QImage and then I immediately delete pImage? The memory should not be deallocated as creating the new QImage has incremented the ref counter. Is this correct?

Thanks!

wysota
16th June 2010, 11:31
mmh... and what about I create the new QImage and then I immediately delete pImage? The memory should not be deallocated as creating the new QImage has incremented the ref counter. Is this correct?
Deleting pImage will decrease the reference count. Look, it doesn't matter whereas you create the object on heap (using "new") or on the stack. The object looks exactly the same in both cases and when you copy it, delete it or do all other possible operations with it, it still behaves the same.