cboe
cboe

Reputation: 477

memcpy underlying data from std::vector of objects

Is this safe or does this just happen to work on my current compiler? Is there anything about this in the standard? The result in the floats vector is correct.

class Color {
public:
  Color(float r, float g, float b, float a) : mColor{r,g,b,a} {};

  inline const float *data() const
  {
    return mColor;
  }

private:
  enum {vectorSize = 4};
  float mColor[vectorSize];
};

//test
std::vector<Color> colors(2);
std::vector<float> floats(8);
colors[0] = Color(0.1, 0.2, 0.3, 0.4);
colors[1] = Color(0.5, 0.6, 0.7, 0.8);
memcpy(floats.data(), colors.data(), 8 * sizeof(float));

Upvotes: 7

Views: 6254

Answers (1)

waTeim
waTeim

Reputation: 9235

It's guaranteed to work

From the standard

23.3.6.1 Class template vector overview

A vector is a sequence container that supports random access iterators. In addition, it supports (amortized) constant time insert and erase operations at the end; insert and erase in the middle take linear time. Storage management is handled automatically, though hints can be given to improve efficiency. The elements of a vector are stored contiguously, meaning that if v is a vector where T is some type other than bool, then it obeys the identity &v[n] == &v[0] + n for all 0 <= n < v.size().

All PODs are trivially copyable

Upvotes: 8

Related Questions