I'm reading notes about reinterpret_cast and it's aliasing rules ( http://en.cppreference.com/w/cpp/language/reinterpret_cast ).
I wrote that code:
struct A
{
int t;
};
char *buf = new char[sizeof(A)];
A *ptr = reinterpret_cast<A*>(buf);
ptr->t = 1;
A *ptr2 = reinterpret_cast<A*>(buf);
cout << ptr2->t;
I think these rules doesn't apply here:
- T2 is the (possibly cv-qualified) dynamic type of the object
- T2 and T1 are both (possibly multi-level, possibly cv-qualified at each level) pointers to the same type T3 (since C++11)
- T2 is an aggregate type or a union type which holds one of the aforementioned types as an element or non-static member (including, recursively, elements of subaggregates and non-static data members of the contained unions): this makes it safe to cast from the first member of a struct and from an element of a union to the struct/union that contains it.
- T2 is the (possibly cv-qualified) signed or unsigned variant of the dynamic type of the object
- T2 is a (possibly cv-qualified) base class of the dynamic type of the object
- T2 is char or unsigned char
In my opinion this code is incorrect. Am I right? Is code correct or not?
On the other hand what about connect function (man 2 connect) and struct sockaddr?
int connect(int sockfd, const struct sockaddr *addr,
socklen_t addrlen);
Eg. we have struct sockaddr_in and we have to cast it to struct sockaddr. Above rules also doesn't apply, so is this cast incorrect?
char buf[sizeof(A)]
and gcc will detect both violations at -Wstrict-aliasing=2 – Mathisonconnect
a C function? – Cutieconnect
method, and specifically - "Above rules also doesn't apply, so is this cast incorrect?" - as I say, the aliasing rules are not about casts. – Marna