Do I need to use pointer to QImage to save memory?
-
wrote on 22 Oct 2021, 00:00 last edited by
I have a
QImage
created and stored as a member variable in a class, and I want to use it in other class, so I created public function that returns theQImage
. I want to reuse the original image to save memory, but I got confused if I should be returning the image itself or a pointer to the image.// somewhere m_image = QImage(); QImage getImage() { return m_image; } QImage * getImage() { return &m_image; }
Which one is the correct way to do it?
-
Returning
QImage
will create a copy of the object. ReturningQImage *
orQImage &
will not copy.However,
QImage
is a implicitly shared class, so as long as you don't modify the object, returningQImage
will not copy the actual image data. -
wrote on 22 Oct 2021, 05:11 last edited by ChrisW67
@lansing No, not usually. QImage (most Qt structures holding larger data) have an internal mechanism that shares the bulk data internally if at all possible. The internal sharing will only cease if a copy is modified. This is generally what you want. For example:
QImage SomeClass::getImage() const { return m_image; }
used like this
QImage img = objSomeClass-> getImage(); // the actual image data is shared between img and objSomeClass->m_image until ... img.setPixel(0, 0, Qt::green); // when a deep copy will be triggered
will do.
Returning a pointer to an actual member variable will allow direct access to the member variable from outside the class. Often a good reason to stop and think about your design.
-
@lansing No, not usually. QImage (most Qt structures holding larger data) have an internal mechanism that shares the bulk data internally if at all possible. The internal sharing will only cease if a copy is modified. This is generally what you want. For example:
QImage SomeClass::getImage() const { return m_image; }
used like this
QImage img = objSomeClass-> getImage(); // the actual image data is shared between img and objSomeClass->m_image until ... img.setPixel(0, 0, Qt::green); // when a deep copy will be triggered
will do.
Returning a pointer to an actual member variable will allow direct access to the member variable from outside the class. Often a good reason to stop and think about your design.
1/4