In the following function
foo(const Mat& img)
img
can be changed in the function without even a warning by the compiler. Why?
That is because a Mat contains a pointer to the actual image data. The const applies only to the Mat object itself (e.g. attributes like rows, cols) and not to the data referred to by the pointer. Note: even if the function was
foo(Mat img)
you could still change the image data.
There are a number of advantages to passing a Mat as const reference. It tells programmers something about how to use foo () and how to modify foo(). Also, it stops you doing things like:
void foo(const cv::Mat& img)
{
img.create(5, 6, CV_8UC3);
}
This will get a compiler error.