Reputation: 395
Can I release memory using this approach?
while(true){
Mat img = imread("C:/image.jpg");
img.refcount = 0;
img.release();
}
What can happen if the memory is deallocated in this way? Assuming that the point indicated is safe.
Upvotes: 3
Views: 4083
Reputation: 11941
If you try to deallocate memory like that you won't succeed. Looking at the source code (see below), if recount is NULL deallocation is not performed. In fact refcount is set to NULL when a Mat is constructed with a pointer to user allocated data.
inline void Mat::release()
{
if( refcount && CV_XADD(refcount, -1) == 1 )
deallocate();
data = datastart = dataend = datalimit = 0;
size.p[0] = 0;
refcount = 0;
}
If on the other hand, as suggested by MariusSiuram, you set what refcount points at to zero, the deallocation will succeed.
But I am not sure why you would want to do that because the destructor for img
will take care of the deallocation for you.
Regarding your comments about erasing Mats in a vector, here is a demonstration:
#include<opencv2/core/core.hpp>
#include "opencv2/highgui/highgui.hpp"
#include <vector>
#include <iostream>
using namespace std;
int main()
{
cv::Mat img = cv::imread("lena.jpg");
cout << "*refcount = " << (*img.refcount) << " should be 1" << endl;
vector<cv::Mat> v;
v.push_back(img);
v.push_back(img);
v.push_back(img);
v.push_back(img);
cout << "*refcount = " << (*img.refcount) << " should be 5" << endl;
auto f = v.begin();
++f;
v.erase(f);
cout << "*refcount = " << (*img.refcount) << " should be 4" << endl;
f = v.end();
--f;
v.erase(f);
cout << "*refcount = " << (*img.refcount) << " should be 3" << endl;
v.resize(0);
cout << "*refcount = " << (*img.refcount) << " should be 1" << endl;
img.release();
cout << "refcount ptr = " << (img.refcount) << " should be 0" << endl;
}
The resulting output is:
*refcount = 1 should be 1
*refcount = 5 should be 5
*refcount = 4 should be 4
*refcount = 3 should be 3
*refcount = 1 should be 1
refcount ptr = 00000000 should be 0
Upvotes: 2