OpenCV(Cpp接口) - 内存管理

时间:2011-10-27 15:28:10

标签: c++ opencv

我发现OpenCV内存管理非常混乱。我在这里阅读了文档http://opencv.itseez.com/modules/core/doc/intro.html#automatic-memory-management,但我真的认为它没有提供足够的信息来完全理解它。

例如,请考虑以下代码段

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;

它有意义吗?有人可以解释它背后的想法吗?

2 个答案:

答案 0 :(得分:5)

你需要分别分配内存来声明矩阵a,b和amp; ç

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

答案 1 :(得分:1)

要全面了解问题,您必须阅读一些关于智能指针的理论http://en.wikipedia.org/wiki/Smart_pointer

OpenCV中的许多对象,包括Mat都被实现为智能指针。