Opencv - 释放内存将cv :: Mat refcount更改为零

时间:2014-09-02 15:00:05

标签: c++ opencv

我可以使用这种方法释放内存吗?

    while(true){
        Mat img = imread("C:/image.jpg");
        img.refcount = 0;
        img.release();
    }

如果以这种方式释放内存会发生什么?假设指出的点是安全的。

1 个答案:

答案 0 :(得分:2)

如果您尝试释放内存,那么您将无法成功。查看源代码(见下文),如果重新计数为NULL,则不执行释放。事实上,当使用指向用户分配数据的指针构造Mat时,refcount设置为NULL。

inline void Mat::release()
{
    if( refcount && CV_XADD(refcount, -1) == 1 )
        deallocate();
    data = datastart = dataend = datalimit = 0;
    size.p[0] = 0;
    refcount = 0;
}

如果另一方面,如MariusSiuram所建议的那样,您将refcount指向的值设置为零,则取消分配将成功。 但是我不确定你为什么要这样做,因为img的析构函数会为你解除分配。

关于在向量中擦除Mats的评论,这是一个演示:

#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; 
}

结果输出为:

*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