Consider the following:
#include <vector>
using namespace std;
struct Vec2
{
float m_x;
float m_y;
};
vector<Vec2> myArray;
int main()
{
myArray.resize(100);
for (int i = 0; i < 100; ++i)
{
myArray[i].m_x = (float)(i);
myArray[i].m_y = (float)(i);
}
float* raw;
raw = reinterpret_cast<float*>(&(myArray[0]));
}
Is raw guaranteed to have 200 contiguous floats with the correct values? That is, does the standard guarantee this?
EDIT: If the above is guaranteed, and if Vec2 has some functions (non-virtual) and a constructor, is the guarantee still there?
NOTE: I realize this is dangerous, in my particular case I have no
choice as I am working with a 3rd party library.
You may add compile time check of structure size:
live demo
It would increase your confidence of your approach (which is still unsafe due to reinterpret_cast, as mentioned).
ISO C++98 9.2/17:
And finally, runtime check of corresponding addresses would make such solution rather safe. It can be done during unit-tests or even at every start of program (on small test array).
Putting it all together:
live demo