Verwenden von memcpy, um den Inhalt eines Vektors <double> in einen Speicherpuffer zu kopieren

Ich habe eine Klasse, die einen Vektor umschließt:

template <typename T>
class PersistentVector
{
  private:
    std::vector<T> values;
  public:
    std::vector<T> & getValues() throw () { return values; }
....
}

Die Instanz ist:

PersistentVector<double> moments;

Ich versuche, eine Kopie aller Doubles in einen von jemand anderem zugewiesenen Puffer zu kopieren. Hier erstelle ich den Puffer:

// invariant: numMoments = 1
double * data_x = new double[numMoments];

Hier ist mein Versuch, den Inhalt des Vektors in den Puffer zu kopieren:

double theMoment = moments.getValues()[0];
// theMoment = 1.33

std::memcpy(
  data_x, 
  &(moments.getValues().operator[](0)), 
  numMoments * sizeof(double));
// numMoments = 1

double theReadMoment = data_x[0];
// theReadMoment = 6.9533490643693675e-310

Wie Sie sehen können, erhalte ich einen Müllwert aus dem Puffer. Warum ist das so?

Funktionierende Lösung

Verwendenstd::copy (Danke an WhozCraig)

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
Fehlgeschlagene Lösung

Versuchendata() Anstatt vonoperator[]()

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

Immer noch neugierig, warum mein ursprünglicher Code versagt!

Antworten auf die Frage(1)

Ihre Antwort auf die Frage