I am trying to optimize a piece of code by not pointer chasing, as much as I currently am. I want to create a constant offset to add to a stored pointer to get to the next data entry, see below code. However, the data is sitting side a class or struct, containing different data types.
So I get the correct behavior in the below code snippet, ie the output is 1, 2, 3.
#include <iostream>
#include <vector>
// knows nothing about foo
class Readfoo
{
private:
int offset;
double* pdouble;
public:
void SetPoint(double* apdouble, int aoffset)
{
offset = aoffset;
pdouble = apdouble;
};
const double& printfoo(int aidouble) const
{
return *(pdouble + offset*aidouble);
};
};
// knows nothing about readFoo
struct foo
{
int a[5];
double b[10];
};
int main()
{
// populate some data (choose b [2] or other random entry.).
std::vector<foo> bar(10);
bar[0].b[2] = 1;
bar[1].b[2] = 2;
bar[2].b[2] = 3;
// access b[2] for each foo using an offset.
Readfoo newReadfoo;
newReadfoo.SetPoint(&(bar[0].b[2]), sizeof(foo)/sizeof(double));
for(int ii = 0; ii < 3; ii++)
{
std::cout<<"\n"<<newReadfoo.printfoo(ii);
}
return 0;
}
My question is two-fold:
- Is this code actually legal, and will it ever produce undefined behavior?
- If it is not legal is there a way to, without storing the actual pointers, iterate through foo accessing b[2], in the above case, with some form of constant offset (Like adding the number of bits between the starting address of each data entry.)?