Implicit sharing and pointers
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:
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!
Re: Implicit sharing and pointers
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.
Re: Implicit sharing and pointers
Quote:
Originally Posted by
Luc4
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.
Re: Implicit sharing and pointers
Quote:
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).
Quote:
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!
Re: Implicit sharing and pointers
Quote:
Originally Posted by
Luc4
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.