Efficiently generating byte buffer without breaking strict aliasing

久未见 提交于 2019-12-04 17:14:31

The safest way to get around aliasing rules is to use memcpy() but you don't need to do that on a whole second copy of the data. I'd suggest doing all your float work on a local float variable and then memcpy()ing that to the appropriate location in your real_data buffer an element at a time. Most compilers will optimize that effectively in my experience.

void better_foo(int c) {
  std::vector<char> real_data(c * sizeof(float));

  //Fill raw_data with usefull stuff...
  for (int i = 0; i < c; ++i) {
    float x = my_complicated_calculation(i);
    memcpy(&real_data[i * sizeof(float)], &x, sizeof(x));
  }

  dispatch(std::move(real_data));
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!