struct Test {
void doAction() {}
};
// Create and save into a void*
void *ptr = new Test;
// Real use through a Test*
Test *t = static_cast<Test *>(ptr);
t->doAction();
// Delete
delete static_cast<Test *>(ptr);
ptr is used only to save the address of the object, and the address is only dereferenced to the true type of the object.
So unless it is dereferenced to an unrelated type, it's ok with the strict aliasing rule ?
Strict aliasing only applies when you are attempting to access the object through a pointer/reference. You are not attempting to access the object through a void*
, so the strict aliasing rule doesn't even apply (the rule that protects you here is the rule on static_cast
that allows it to convert a pointer to any type to void*
and back, so long as the type you cast it back to is exactly the type it was before).
Similarly, pointers to the same type are allowed to alias. So t
and the result of static_cast<T*>
are allowed to alias and thus having both do not violate strict aliasing.