7

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)); 
1

1 Answer 1

8

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

Sign up to request clarification or add additional context in comments.

4 Comments

That doesn't guarantee his code will work. What assures sizeof(Color) == (4 * sizeof(float))? If that's not true, his code breaks horribly.
That's exactly why I wasn't sure. But why would it not equal 4 * sizeof(float)?
As Color is written now, the size of a Color obj will be 4 * sizeof(float). However, Color could easily be changed such that this is no longer true. I believe this code is guaranteed to work as written, but it is very brittle.
Since there's no more activity on this question I'll accept this as the answer. I agree that it's brittle, however, my Color class is unlikely to change and I need to copy lots and lots of them. I've added a static_assert that checks sizeof(Color) == (4 * sizeof(float)) to at least get a notice if I should accidentally change the Color class implementation or if another compiler would change the size of the object.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.