title: How can I reserve a fixed buffer size in OpenCV Mat?
body: <p>I am rewriting some legacy code that does matrix operations on doubles using a raw C-style array. Since the code already has a dependency on OpenCV somewhere else, I want to use the <code>cv::Mat</code> class instead.</p>
  
  <p>The specific code that bothers me works on square matrixes from size 1*1 to N<em>N. It does so by allocating an N</em>N buffer and uses a subset of it for smaller matrixes.</p>
  
  <pre class="lang-cpp prettyprint-override"><code>double* buf = new double[NxN];
  for (int i = 1; i &lt; N; ++i) {
      // Reuse buf to create a i*i matrix and perform matrix operations
      ...
  
  }
  delete[] buf;
  
  </code></pre>
  
  <p>Basically, I want to replace that code to use <code>cv::Mat</code> objects in the loop instead. Problem is, the code requires a lot of loop iterations (there are nested loops and so on) and there are too many allocations/deallocations if I just use the naïve and clean approach. Therefore, I want to reserve the size of my matrix object beforehand and resize it for each iteration. This would ideally look like this:</p>
  
  <pre class="lang-cpp prettyprint-override"><code>cv::Mat m;
  m.reserveBuffer(N * N * sizeof(double));
  for (int i = 1; i &lt; N; ++i) {
      m = cv::Mat(i, i, CV_64F);
      // Perform matrix operations on m
      ...
  
  }
  </code></pre>
  
  <p>But in my understanding this would simply drop the previous instance of <code>m</code> and then allocate a i*i matrix. What would the right approach be?</p>