Cleaner way to convert an array of compact float values into an array of floats

余生颓废 提交于 2021-01-29 21:12:28

问题


Before the actual question, small prelude. I don't care about security, I do care about performance. I KNOW this is not proper and I know it's very hacky, however this is quite fast.

vector<float> result = move(*((vector<float>*)&vertices));

That code is abusing C style casts and pointers to force the compiler to interpret the left hand side array vertices which is a vector of a compact type where all the fields are float as an array of floats.

i.e

struct vertex {
   float x;
   float y;
   float z;
}
vector<vertex> vertices;

This works and does what it needs to, however it's somewhat hard to read. I want to know if there is another way of achieving the same outcome in a more readable way.


回答1:


What you should care more about is that the behaviour of your code is undefined since the cast is a violation of the strict aliasing rule. Note that vector<vertex> is a completely different type to a vector<float>.

In particular you are assuming the data in the struct are contiguous and there is no padding in the struct, even at the end.

Why not use a vector<float> from the get-go, with a note to self that the 4th element starts the next triangle, and so on?



来源:https://stackoverflow.com/questions/61374833/cleaner-way-to-convert-an-array-of-compact-float-values-into-an-array-of-floats

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