void foobar(Base* base)
{
Derived* derived = dynamic_cast<Derived*>(base); // or static_cast
derived->blabla = 0xC0FFEE;
if (base->blabla == 0xC0FFEE)
...
}
On compilers 开发者_如何学Cwith strict aliasing, is "derived" an alias for "base"?
Two pointers are aliased whenever it is possible to access the same object through them. Paragraph 3.10/15 of the standard specifies when an access to an object is valid.
If a program attempts to access the stored value of an object through an lvalue of other than one of the following types the behavior is undefined:
- the dynamic type of the object,
- a cv-qualified version of the dynamic type of the object,
- a type that is the signed or unsigned type corresponding to the dynamic type of the object,
- a type that is the signed or unsigned type corresponding to a cv-qualified version of the dynamic type of the object,
- an aggregate or union type that includes one of the aforementioned types among its members (including, recursively, a member of a subaggregate or contained union),
- a type that is a (possibly cv-qualified) base class type of the dynamic type of the object,
- a char or unsigned char type.
In your case, *derived
is either an l-value of the dynamic type of the object or it is of a type that is a base class type of the dynamic type of the object. *base
is of a type that is a base class type of the dynamic type of the object.
Therefore, you are allowed to access the object through both derived
and base
, making the two pointers aliased.
精彩评论