2014-09-02 135 views
2

可以使用此方法釋放內存嗎?Opencv - 釋放內存將cv :: Mat引用計數器更改爲零

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

如果內存以這種方式釋放,會發生什麼情況?假設所指出的點是安全的。

+2

也許你的意思是「*(img.refcount)= 0; 「 (refcount本身就是一個指針) – MariusSiuram 2014-09-02 15:11:38

+2

你爲什麼要這麼做? – Bull 2014-09-02 16:05:42

+4

你不會*想要手動調整refcounts;) – berak 2014-09-02 17:40:45

回答

2

如果你試圖釋放這樣的內存,你將不會成功。查看源代碼(請參閱下文),如果recount爲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的建議,你設定在零引用計數什麼百分點,釋放一定會成功。 但我不確定爲什麼你會這樣做,因爲img的析構函數會爲您解除分配。

關於你提到的有關在矢量擦除墊評論,這裏是一個演示:

#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 
+0

Tks B ...閱讀您的回覆後,我開始瞭解refcount是如何工作的。然後我只是在我的代碼中進行調試,檢查引用計數已更改的位置,並找到內存泄漏的位置,並在cv :: Mat對象中釋放。現在我的代碼工作正常。非常感謝! – rwvaldivia 2014-09-09 14:23:20