to catch the case above, you just can check mat.data for equality:
Mat a=Mat::ones(3,3,CV_8U)*1;
Mat b=Mat::ones(3,3,CV_8U)*2;
cerr << "a" << a << " " << long(a.data) << endl;
cerr << "b" << b << " " << long(b.data) << endl;
cerr << "a==b " << (a.data==b.data) << endl;
b = a; // same pointer
cerr << "b" << b << " " << long(b.data) << endl;
cerr << "a==b " << (a.data==b.data) << endl;
a[1, 1, 1;
1, 1, 1;
1, 1, 1] 3826464
b[2, 2, 2;
2, 2, 2;
2, 2, 2] 3826544
a==b 0
b[1, 1, 1;
1, 1, 1;
1, 1, 1] 3826464
a==b 1
also, there's another interesting case, where a and b don't share memory, but still have the same pixels:
Mat c=Mat::ones(3,3,CV_8U)*3;
cerr << "c" << c << " " << long(c.data) << endl;
cerr << "a==c " << (a.data==c.data) << endl;
c = a.clone(); // same pixels, different pointer
cerr << "a==c " << (a.data==c.data) << endl;
cerr << "a==c " << (a==c) << endl;
cerr << "a==c " << cv::norm(a,c,CV_L1) << endl;
c[3, 3, 3;
3, 3, 3;
3, 3, 3] 3826544
a==c 0
a==c 0
a==c [255, 255, 255;
255, 255, 255;
255, 255, 255]
a==c 0