Does the following program invoke undefined behavior? Assume the programmer has enough knowledge of ABI and class layout. The main thing that I am suspicious of is the line p1 += 2;
, but I appreciate your comment on any other issue.
Please consider two cases: compiled with and without fno-strict-aliasing
#include <iostream>
using namespace std;
class X {
public:
float f1;
int i1;
X() {
f1 = 0;
i1 = 0;
f2 = 5.1;
i2 = 1;
}
int *getPointer() { return &i1; }
private:
float f2;
int i2;
};
int main() {
X x;
int *p1 = x.getPointer();
p1 += 2;
cout << *p1 << "\n";
*p1 = 2;
cout << *p1 << "\n";
return 0;
}