简体   繁体   English

来自std :: vector对象的memcpy底层数据

[英]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));

It's guaranteed to work 它保证工作

From the standard 从标准

23.3.6.1 Class template vector overview 23.3.6.1类模板矢量概述

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(). 向量的元素是连续存储的,这意味着如果v是一个向量,其中T是某种类型而不是bool,那么它服从所有0 <= n <v的身份&v [n] ==&v [0] + n 。尺寸()​​。

All PODs are trivially copyable 所有POD都可以轻易复制

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM