Below has 3 different styles for indirect accessing. I am trying to understand if they all have well-defined behavior, and can be safely used for cross-platform code.
#include <cstdint>
#include <iostream>
#include <any>
using namespace std;
#if 1
#define INLINE [[gnu::always_inline]] inline
#else
#define INLINE [[gnu::noinline]]
#endif
INLINE
void mod1(void *p) {
*static_cast<int*>(p) = 10;
}
INLINE
void mod2(uintptr_t p) {
*reinterpret_cast<int*>(p) = 12;
}
INLINE
void mod3(any p) {
*any_cast<int*>(p) = 14;
}
int test1() {
int a1 = 5;
mod1(&a1);
return a1;
}
int test2() {
int a2 = 6;
mod2(reinterpret_cast<uintptr_t>(&a2));
return a2;
}
int test3() {
int a3 = 6;
mod3(&a3);
return a3;
}
int main() {
cout << test1() << "\n";
cout << test2() << "\n";
cout << test3() << "\n";
}
I tried inline and noinline, they all work as expected, output 10 12 14 so I think inlining does not matter here.
Are they all well-defined behavior by C++ standard? Any help would be greatly appreciated :)
[Edit] Even if we consider type-based alias analysis.