The rules surrounding strict aliasing can be quite tricky.
An example of strict aliasing is:
int a = 0;
float* f = reinterpret_cast<float*>(&a);
f = 0.3;
printf("%d", a);
This is a strict aliasing violation because:
- the lifetime of the variables (and their use) overlap
- they are interpreting the same piece of memory through two different "lenses"
If you are not doing both at the same time, then your code does not violate strict aliasing.
In C++, the lifetime of an object starts when the constructor ends and stops when the destructor starts.
In the case of built-in types (no destructor) or PODs (trivial destructor), the rule is instead that their lifetime ends whenever the memory is either overwritten or freed.
Note: this is specifically to support writing memory managers; after all malloc
is written in C and operator new
is written in C++ and they are explicitly allowed to pool memory.
I specifically used lenses instead of types because the rule is a bit more difficult.
C++ generally use nominal typing: if two types have a different name, they are different. If you access a value of dynamic type T
as if it were a U
, then you are violating aliasing.
There are a number of exceptions to this rule:
- access by base class
- in PODs, access as a pointer to the first attribute
And the most complicated rule is related to union
where C++ shifts to structural typing: you can access a piece of memory through two different types, if you only access parts at the beginning of this piece of memory in which the two types share a common initial sequence.
§9.2/18 If a standard-layout union contains two or more standard-layout structs that share a common initial sequence, and if the standard-layout union object currently contains one of these standard-layout structs, it is permitted to inspect the common initial part of any of them. Two standard-layout structs share a common initial sequence if corresponding members have layout-compatible types and either neither member is a bit-field or both are bit-fields with the same width for a sequence of one or more initial members.
Given:
struct A { int a; };
struct B: A { char c; double d; };
struct C { int a; char c; char* z; };
Within a union X { B b; C c; };
you can access x.b.a
, x.b.c
and x.c.a
, x.c.c
at the same time; however accessing x.b.d
(respectively x.c.z
) is a violation of aliasing if the currently stored type is not B
(respectively not C
).
Note: informally, structural typing is like mapping down the type to a tuple of its fields (flattening them).
Note: char*
is specifically exempt from this rule, you can view any piece of memory through char*
.
In your case, without the definition of Data
I cannot say whether the "lenses" rule could be violated, however since you are:
- overwriting memory with
Data
before accessing it through Data*
- not accessing it through
int*
afterwards
then you are compliant with the lifetime rule, and thus there is no aliasing taking place as far as the language is concerned.