implicitly casting away cv::Mat constness (Feature #2317)
Description
While porting some code from using the old IplImage to using cv::Mat, I noticed that it's all too easy to accidentally cast away the constness of cv::Mat. A simple example:
const cv::Mat mat_const(3,1,CV_32FC1,data);
cv::Mat mat_non_const = mat_const;
//modifying mat_non_const also modifies mat_const !!!
It seems that this is a huge problem that opens the door to all kinds of bugs. Is there some alternative way for dealing with and ensuring constness (or at least making it hard and more explicit to cast it away)?
Associated revisions
Merge pull request #2317 from blueskymonster:master
History
Updated by Vadim Pisarevsky over 12 years ago
I doubt we can solve it easily. It's not a bug, it's just the way how C++ works. I do not see a solution other than to introduce a separate const_Mat class, but this is big effort to make it properly.
Let's mark it as low-priority feature for 2.5. May be, in a few months from now we will see how to do it or maybe someone proposes a patch.
- Category set to core
- Priority changed from Normal to Low
- Target version set to 3.0
- Tracker changed from Bug to Feature
- Assignee set to Vadim Pisarevsky
Updated by Adi Shavit almost 12 years ago
You could actually define the non-const assignment operator only for non-const cv::Mat, and a const assignment operator for const cv::Mat.
Then when attempting to copy from a const cv::Mat you'd get a compilation error if the target is non-const, at which point you could either define it as const or use clone().
Updated by Maksim Shabunin over 9 years ago
Issue has been transferred to GitHub: https://github.com/Itseez/opencv/issues/4420