2

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.

TheWaterProgrammer
  • 7,055
  • 12
  • 70
  • 159

1 Answers1

6

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.

user1095108
  • 14,119
  • 9
  • 58
  • 116
  • Understand that `const_cast` is discouraged. BUT, if I do a const_cast like this `QImage copy = const_cast(img)` then do `copy = QImage()`. **Will this clean up `img`?** – TheWaterProgrammer Sep 18 '17 at 09:33
  • If I use a shared_ptr then I would not have to worry about the clean up? – TheWaterProgrammer Sep 18 '17 at 09:38
  • 1
    The problem is that Qt uses COW on many of it's classes, like QImage, QByteArray, ... So when you copy any of these you just create a new reference to the same data. You need to make sure all references to the same data (i.e. all QImage instances referencing the same image) are destroyed to free up the referenced image data. – user1095108 Sep 18 '17 at 10:23