I have a class that wraps a vector:
template <typename T>
class PersistentVector
{
private:
std::vector<T> values;
public:
std::vector<T> & getValues() throw () { return values; }
....
}
The instance is:
PersistentVector<double> moments;
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:
// invariant: numMoments = 1
double * data_x = new double[numMoments];
Here is my attempt at copying the contents of the vector into the buffer:
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
As you can see, I am getting a garbage value from the buffer. Why is this so?
Working solution
Use std::copy
(thanks to 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
Failed solution
Try data()
instead of operator[]()
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
Still curious as to why my original code is failing!