Based on a comment and answer on my other question I came out with this code. The comment was according to 5.3.4 New [expr.new] it is allowed to access outside of the struct as long as it is allocated. However I coudln't find the section that says that.
I came up with this code. I wanted to know if its portable and completely defined and legal. The output is kind of interesting. in gcc it is 10,10,12 while visual studios 2010 shows 12,10,12.
Is the code legal in C++11 or C++03? I believe the code will be align in any platform/cpu with a standard compiler.
-edit- In case your lazy flex_struct is the part that does questionable things.
#include <iostream>
#include <new>
#include <cstring>
using namespace std;
template <typename STRUCT, typename TYPE> class flex_struct {
flex_struct(){}
public:
//should be safe to access and check what length the array is
static STRUCT* head(char*buff) {
//is this next line wrong?
//if((alignof(STRUCT)%reinterpret_cast<size_t>(buff))!=0) { throw std::exception(); }
return reinterpret_cast<STRUCT*>(buff);
}
struct struct_with_array : public STRUCT { TYPE buf[1]; };
TYPE* buff() {
//if(length==0) { throw std::exception(); }
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];
//we don't actually need this line which is incorrect anyways (sizeof isnt 1024)
//memset(srcarray, 0, sizeof(srcarray)); //whats a C++ way to do this w/o writing a loop or function?
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);
}