I was looking an example of Modern OpenGL in c++ where a structure is used to hold data regarding vertex coordinates and a 3 coordinate color vector
struct VertexData{
float x, y;
float r, g, b;
}
std::vector<VertexData> myData = {
{.x = 0, .y = 0, .r = 0, .g = 0, .b = 0},
{.x = 0, .y = 0, .r = 0, .g = 0, .b = 0}
}
float *ptr = (float*) &myData[0];
To access the x value of the second element of the vector, I could acces ptr[5]
, technique used to pass a vertex buffer to OpenGL. My question is: Can I use this same technique with a more complex class? As a concrete example, if I have a Vertex
class:
class Vertex {
public:
float x, y, z;
Vertex();
// Other constructors here...
Vertex operator+(const Vertex &other);
// Overload of other operators like -,*,=, etc...
}
std::vector<Vertex> myData(100);
float *ptr = (float*) &myData[0];
would it still be safe (and a good idea...) to use the ptr
variable to access all elements in this vector? I know this could be tricky in the presence of static variables, different types, inheritance and so on, but in this case were there are only plain variables and functions as members, would using a pointer be a reliable approach?