Based on the comments and answering my other question , I came out with this code. The comment was in accordance with 5.3.4 New [expr.new] and was allowed access outside the structure as long as it was allocated. However, I cannot find the section that says that.
I came up with this code. I wanted to know if its portable and fully defined and legal. The result is interesting. in gcc it's 10,10,12, and visual studios 2010 show 12,10,12.
Is the code legal in C ++ 11 or C ++ 03? I believe that the code will be aligned on any platform / processor with a standard compiler.
-edit- If your lazy flex_struct is the part that causes the dubious things.
#include <iostream>
#include <new>
#include <cstring>
using namespace std;
template <typename STRUCT, typename TYPE> class flex_struct {
flex_struct(){}
public:
static STRUCT* head(char*buff) {
return reinterpret_cast<STRUCT*>(buff);
}
struct struct_with_array : public STRUCT { TYPE buf[1]; };
TYPE* buff() {
auto p = reinterpret_cast<struct_with_array*>(this);
return p->buf;
}
};
typedef short testtype;
struct MyVariableLengthStruct : public flex_struct<MyVariableLengthStruct, testtype> {
int a, b;
char c;
};
struct MyVariableLengthStruct2 {
int a, b;
char c;
testtype buf[1];
};
struct MyVariableLengthStruct3a {
int a, b;
char c;
};
struct MyVariableLengthStruct3 : MyVariableLengthStruct3a {
testtype buf[1];
};
int main() {
auto srcarray=new char[1024];
auto v = MyVariableLengthStruct::head(srcarray);
auto buff = v->buff();
auto dif1 = (int)buff-(int)v;
printf("%X %X %d\n", v, buff, dif1);
MyVariableLengthStruct2 v2;
auto dif2 = (int)v2.buf-(int)&v2;
printf("%X %X %d\n", &v2, v2.buf, dif2);
MyVariableLengthStruct3 v3;
auto dif3 = (int)v3.buf-(int)&v3;
printf("%X %X %d\n", &v3, v3.buf, dif3);
}
user34537