I've searched thoroughly and have not found a straightforward answer to this.
Passing opencv matrices (cv::Mat
) as arguments to a function, we're passing a smart pointer. Any change we do to the input matrix inside the function alters the matrix outside the function scope as well.
I read that by passing a matrix as a const reference, it is not altered within the function. But a simple example shows it does:
void sillyFunc(const cv::Mat& Input, cv::Mat& Output){
Output = Input;
Output += 1;
}
int main( int argc, char** argv ){
cv::Mat A = cv::Mat::ones(3,3,CV_8U);
std::cout<<"A =
"<<A<<"
";
cv::Mat B;
sillyFunc(A,B);
std::cout<<"A =
"<<A<<"
";
std::cout<<"B =
"<<B<<"
";
}
Clearly, A
is altered even though it is sent as a const cv::Mat&
.
This does not surprise me as within the function I2
is a simple copy of I1
's smart pointer and thus any change in I2
will alter I1
.
What does baffle me is that I don't understand what practical difference exists between sending cv::Mat
, const cv::Mat
, const cv::Mat&
or cv::Mat&
as arguments to a function.
I know how to override this (replacing Output = Input;
with Output = Input.clone();
would solve the problem) but still don't understand the above mentioned difference.
Thanks guys!
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…