Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

c++ - OpenCV Mat::operator= - does it support copy on write?

From the OpenCV documentation, it appears that copying a matrix is done using a shallow copy, but when changing one of the copies, a copy is done.

The exact reference is:

Mat& Mat::operator = (const Mat& m)

Mat& Mat::operator = (const MatExpr_Base& expr)

Mat& operator = (const Scalar& s)

Matrix assignment operators

Parameters:

m – The assigned, right-hand-side matrix. Matrix assignment is O(1) operation, that is, no data is copied. Instead, the data is shared and the reference counter, if any, is incremented. Before assigning new data, the old data is dereferenced via Mat::release .

expr – The assigned matrix expression object. As opposite to the first form of assignment operation, the second form can reuse already allocated matrix if it has the right size and type to fit the matrix expression result. It is automatically handled by the real function that the matrix expressions is expanded to. For example, C=A+B is expanded to cv::add(A, B, C) , and add() will take care of automatic C reallocation.

s – The scalar, assigned to each matrix element. The matrix size or type is not changed.

However, this appears not to work

Mat_<float> a(5,5),b(5,5);
a =1;
b = a;
a = 2;

now b == 2, intead of 1

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It seems you misunderstood. "Before assigning new data, the old data is dereferenced via Mat::release" does not mean that when you write on a or b then a copy occurs. It means that when you type b=a, you lose the data that was in b.

Long story short : copy on write is not supported.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...