2011-10-27 31 views
1

我發現OpenCV內存管理相當混亂。我在這裏閱讀文檔http://opencv.itseez.com/modules/core/doc/intro.html#automatic-memory-management,但我真的不認爲它提供了足夠的信息來完全理解它。OpenCV(Cpp接口) - 內存管理

例如,考慮下面的代碼片段

Mat_<float> a,b,c; 

a = b; // The header of b is copied into a and they share the data 
b = c; // Now b refers to c and a != b 
b = a + 1; // b still shares data with c and s.t. b = c; 

這有什麼意義嗎?有人可以解釋它背後的想法嗎?

回答

5

你需要從宣佈矩陣分別分配內存A,B &Ç

cv::Mat b(10, 10, CV8U_C1); //this allocates 10 rows and 10 columns of 8 bit data to matrix b 
cv::Mat a; //This defines a matrix with an empty header. You *cannot* yet assign data to it - trying to do so will give a segmentation fault 
a = b; //matrix a is now equal to matrix b. The underlying data (a pointer to 10 x 10 uints) is shared by both so it is a shallow copy (and thus very efficient). However modifying the data in martix a will now modify the data in matrix b 
cv::Mat c(10, 10, CV8U_C1); 
b = c;  //This will change matrix b to point to the newly allocated data in matrix c. Matrix a now has the sole access to its data as matrix b no longer shares it. Matrix b and c share the same data; 
b = a + 1 //This statement makes no sense. Even if it is valid you should never use it - it is completely unclear what it does 
+0

爲什麼b = a + 1沒有意義?幾乎每一個linalg庫都會重載操作符,所以我想這很常見。它只是一個元素明智的補充。我的問題是:爲什麼b = a + 1; // b仍然與c和s.t.共享數據b = c; b不應該與c分享數據吧?它應該指向新分配的矩陣a + 1; – memecs

1

有關問題的一般理解,你必須讀一些理論關於智能指針http://en.wikipedia.org/wiki/Smart_pointer

在OpenCV的許多物體,包括Mat被實現爲智能指針。

+0

我知道,但考慮到電話b = a + 1;首先(a + 1)生成一個新的矩陣Mat算子+(Mat,Scalar),那麼這個新的矩陣被分配給b。因此,不應該將b指向新的(a + 1)矩陣而不是將數據複製到其指向的內存中? – memecs

+0

Mat對象的設計使其在新分配的對象具有與以前相同的大小時不會重新創建內存。所以結果保存在舊的數據空間中,這實際上是由矩陣c和b共享的空間。如果給b分配一個更大的矩陣(b.create(10,10,CV_8UC1)),舊的數據指針將僅用於c,而b將有自己的空間。 – Sam

+0

我明白了。聽起來真的很容易出錯,他們應該改變它。感謝 – memecs