Important: Please read the Qt Code of Conduct -

[SOLVED] Implicit Sharing and Pointers

  • Greetings.

    I've been reading about the feature 'Implicit Sharing' Qt classes and I doubt has arisen as follows:

    Is this feature works just when working with pointers and not directly with objects?


    /* img1 and img2 being kind QImage objects: QImage img1, img2; */

    img1 = img2; // Here img1 and img2 share the data

    But in the case:
    /* img1 and img2 as QImage pointers: QImage *img1, *img2; */

    *img1 = *img2; // img1 and img2 share the data or not?

    So are both equivalent or am I wrong?

    Thanks in advance for any responses and/or comments.

  • If img1 and img2 are auto-objects of type QImage then
    @img1 = img2;@
    ...will call the assignment operator of the first object and pass the second object.

    So it's actually:

    Now if you have pointers to QImage objects and you are dereferencing these pointers, it's the same thing!
    @*img1 = *img2@

    ...actually does:

    Consequently, if "Implicit Sharing" is implemented for QImage (and thus in the assignment operator of QImage), then this will work the same way in both cases. The implementation of the assignment operator in QImage cannot know whether it has been called form an auto-object or from a pointer...


    BTW: It should be clear that if you have pointers and are not dereferencing them, it won't work!

    Assuming img1 and img2 are pointers to QImage objects:
    @img1 = img2@

    ...will cause img1 to point to the same object as img2, while the object to which img1 pointed before remains completely unaffected (we simply lost the pointer to that object). Now any change to img1 will be "visible" in img2 (and vice versa), because they point to the very same object. That's different from what "Implicit Sharing" does!

  • Thanks, that was a bit silly question ... I just wanted to be absolutely sure

Log in to reply