Do I need to use pointer to QImage to save memory?
-
I have a
QImagecreated 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
QImagewill create a copy of the object. ReturningQImage *orQImage &will not copy.However,
QImageis a implicitly shared class, so as long as you don't modify the object, returningQImagewill not copy the actual image data. -
@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 triggeredwill 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 triggeredwill 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.