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));
You can use the Use memcpy for vector assignment parameter to optimize generated code for vector assignments by replacing for loops with memcpy function calls. The memcpy function is more efficient than for -loop controlled element assignment for large data sets. This optimization improves execution speed.
Profiling shows that statement: std::copy() is always as fast as memcpy() or faster is false.
std::vector::swap is not copying a vector to another, it is actually swapping elements of two vectors, just as its name suggests.
The memcpy function copies n bytes from ct to s. If these memory buffers overlap, the memcpy function cannot guarantee that bytes in ct are copied to s before being overwritten.
Trying to memcpy a vector is in short undefined behavior. Use normal assignment or std::copy to copy it. I don't think I would call it undefined behavior.
std::memcpy may be used to implicitly create objects in the destination buffer. std::memcpy is meant to be the fastest library routine for memory-to-memory copy.
std::memcpy is meant to be the fastest library routine for memory-to-memory copy. It is usually more efficient than std::strcpy, which must scan the data it copies or std::memmove, which must take precautions to handle overlapping inputs. Several C++ compilers transform suitable memory-copying loops to std::memcpy calls.
If either dest or src is an invalid or null pointer, the behavior is undefined, even if count is zero. If the objects are potentially-overlapping or not TriviallyCopyable, the behavior of memcpy is not specified and may be undefined . std::memcpy may be used to implicitly create objects in the destination buffer.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With