Qt: How to clean up a QImage from memory

4.9k views Asked by At

How to clear or clean up a QIMage

Following method of mine get a const reference to a QIMage.

MyMethod(const QImage & img) {

  // save it to a file
  img.save("/path/to/save/the/qimage");

  // now I want to clan up img from memory. How should I do it? 
}

Question:
How should I clean up the QImage object from memory after use?

Note:
Note that it is a const & QImage. So, answer would involve casting the QImage into non-const? Also, I am looking at trying to get a QImageData pointer to the data & delete it. Not sure if that is the correct approach here. Do suggest.

1

There are 1 answers

3
user1095108 On BEST ANSWER

You need a non-const reference or a pointer. With a pointer the answer is obvious. With a reference you just assign a default-constructed QImage to it.

MyMethod(QImage & img) {
  img.save("/path/to/save/the/qimage");

  img = QImage();
}

However, this may still not clean up the memory occupied by the image, if there are additional QImage instances referencing that same image. To overcome this hurdle you need to avoid multiple QImage instances referencing the same image. A Qimage instance is like a shared pointer in this regard.

A const-cast would be considered to reveal a design flaw in your case. I'd recommend against it.