title: Using memcpy to copy the contents of a vector<double> into a memory buffer
body: <p>I have a class that wraps a vector:</p>
  
  <pre><code>template &lt;typename T&gt;
  class PersistentVector
  {
    private:
      std::vector&lt;T&gt; values;
    public:
      std::vector&lt;T&gt; &amp; getValues() throw () { return values; }
  ....
  }
  </code></pre>
  
  <p>The instance is:</p>
  
  <pre><code>PersistentVector&lt;double&gt; moments;
  </code></pre>
  
  <p>I am trying to make a copy of all the doubles into a buffer allocated by somebody else.  Here is where I create the buffer:</p>
  
  <pre><code>// invariant: numMoments = 1
  double * data_x = new double[numMoments];
  </code></pre>
  
  <p>Here is my attempt at copying the contents of the vector into the buffer:</p>
  
  <pre><code>double theMoment = moments.getValues()[0];
  // theMoment = 1.33
  
  std::memcpy(
    data_x, 
    &amp;(moments.getValues().operator[](0)), 
    numMoments * sizeof(double));
  // numMoments = 1
  
  double theReadMoment = data_x[0];
  // theReadMoment = 6.9533490643693675e-310
  </code></pre>
  
  <p>As you can see, I am getting a garbage value from the buffer.  Why is this so?</p>
  
  <h2>Working solution</h2>
  
  <p>Use <code>std::copy</code> (thanks to WhozCraig)</p>
  
  <pre><code>double theMoment = moments.getValues()[0];
  // theMoment = 1.33
  
  std::copy(moments.getValues().begin(), moments.getValues().end(), data_x);
  
  double theReadMoment = data_x[0];
  // theReadMoment = 1.33
  </code></pre>
  
  <h2>Failed solution</h2>
  
  <p>Try <code>data()</code> instead of <code>operator[]()</code></p>
  
  <pre><code>double theMoment = moments.getValues()[0];
  // theMoment = 1.33 
  
  std::memcpy(
    data_x, 
    moments.getValues().data(),
    numMoments * sizeof(double));
  // numMoments = 1
  
  double theReadMoment = data_x[0];
  // theReadMoment = 6.9533490643693675e-310
  </code></pre>
  
  <p><strong>Still curious as to why my original code is failing!</strong></p>