title: Is cv::Mat class flawed by design?
body: <p>I work a lot with the OpenCV C++ interface and designed a number of classes which use Mat's as private resources. </p>
  
  <p>Recently, I got concerned about the Mat class, as it always uses image data as shared resource unless I explicitly call clone. <strong>Even if I write <code>const Mat</code> I can't be sure that the imagedata does not get changed later from the outside.</strong></p>
  
  <p>So I need to clone to ensure encapsulation. But the problem with needing to explicitly clone a Mat is that it is often unnecessary and expensive. On the other hand I understand that the need for shared imagedata originates from roi selectors, and being able to write something like this:
  <code>Mat m_small = m_big(my_roi)</code>.</p>
  
  <p>My questions are:</p>
  
  <p>1.) <strong>Should not the cv::Mat class be rather lazily cloned?</strong> So the user will not see Mat's as shared resource handlers from the outside. Should not the user explicitly instantiate a class called something like <code>SharedMat</code> when a real shared imagedata is needed?<br>
  2.) Do you have any <strong>better strategy than always cloning</strong> in case of cv::Mat as private resource for a class?</p>
  
  <hr>
  
  <p>UPDATE: "you do not use <code>Mat::clone()</code>  unless you plan to modify the data." (by Vadim Pisarevsky)<br>
  <em>This idea has a problem.</em>
  Consider the situation that you have this class:</p>
  
  <pre><code>class Res_handler{
  public:
    const Mat emit_mat(){ return m_treasure; } // I argue you are compelled to clone here.
  private:
    Mat m_treasure;
  };
  </code></pre>
  
  <p>If you do not <code>clone</code> in this case you can write</p>
  
  <pre><code>Mat m_pirate = res_handler.emit_mat(); m_pirate = Scalar(0,0,0);
  </code></pre>
  
  <p>which causes a full black-out in the <code>m_treasure</code> inside the <code>res_handler</code> through the shared image data between <code>m_pirate</code> and <code>m_treasure</code>. :) So to avoid accidental modification of the inner <code>m_treasure</code>, <em>you need to <code>clone</code> it</em>.</p>
  
  <p>On the other hand, this solution is also flawed:</p>
  
  <pre><code>const Mat m_pirate = res_handler.emit_mat(); 
  </code></pre>
  
  <p>because <code>m_treasure</code> can get modified too, so the content of <code>m_pirate</code> gets changed in the background, causing great headache to the pirate's programmer. :)</p>