How to implement the imshowCompare() function without memory leak?
I implemented the imshowCompare() function that switch the output and the original image by the left mouse button click in cv::imshow windows. This is a very useful function for testing. The code is as follows, but can not solve the problem of memory leak.
void on_MouseHandle_Compare(int event, int x, int y, int flags, void* param);
typedef struct {
String winname;
Mat src;
Mat dst;
} strImshowCompare;
void imshowCompare(const String& winname, const Mat& src, const Mat& dst)
{
// src, dst must be cloned, otherwise the external Mat may be modified.
Mat newsrc = src.clone(); // Their memory will leak.
Mat newdst = dst.clone(); // Their memory will leak.
cv::imshow( winname, newdst);
// struct strImshowCompare can't delete in this function! It must delete after the window is closed. But I don't know when the window is closed.
strImshowCompare* str = new strImshowCompare;
str->winname = winname;
str->src = newsrc;
str->dst = newdst;
cv::setMouseCallback(winname, on_MouseHandle_Compare, (void *)str);
}
void on_MouseHandle_Compare(int event, int x, int y, int flags, void* param)
{
strImshowCompare* str = (strImshowCompare*) param;
switch (event) {
case cv::EVENT_LBUTTONDOWN: {
cv::imshow(str->winname, str->src);
break;
}
case cv::EVENT_LBUTTONUP: {
cv::imshow(str->winname, str->dst);
break;
}
}
}
I don't know for the memory leak but at least you should be able to do something like that:
Yes, we can pass the pointer, and then manually release it. The bad thing is that it's easy to forget to release. Change raw pointer to smart pointer may solve this problem. But pass a pointer was also verbosely. Hope to have the simple calling way like imshowCompare("winname", src, dst).