gpt4 book ai didi

c++ - 来自 std::vector of objects 的 memcpy 底层数据

转载 作者:可可西里 更新时间:2023-11-01 18:29:28 25 4
gpt4 key购买 nike

这是安全的还是恰好适用于我当前的编译器?标准中有关于此的内容吗?浮点 vector 中的结果是正确的。

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

最佳答案

保证有效

来自标准

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().

所有 POD 都是可简单复制的

关于c++ - 来自 std::vector of objects 的 memcpy 底层数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21592196/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com