2023-09-20 14:18:08 +02:00

52 lines
1.2 KiB
Plaintext

== Why is this an issue?
Casting from a virtual base to a derived class, using any means other than `dynamic_cast` has undefined behavior. The behavior for `dynamic_cast` is defined.
Note: As of {cpp}17, the program is considered ill-formed, and an error is reported.
Most compilers emit an error for previous versions of {cpp} as well.
=== Noncompliant code example
[source,cpp,diff-id=1,diff-type=noncompliant]
----
class B { ... };
class D: public virtual B { ... };
D d;
B *pB = &d;
D *pD1 = ( D * ) pB; // Noncompliant - undefined behavior
D *pD2 = static_cast<D*>(pB); // Noncompliant - undefined behavior
----
=== Compliant solution
[source,cpp,diff-id=1,diff-type=compliant]
----
class B { ... };
class D: public virtual B { ... };
D d;
B *pB = &d;
D *pD1 = dynamic_cast<D*>(pB); // Compliant, but pD2 may be NULL
D & D2 = dynamic_cast<D&>(*pB); // Compliant, but may throw an exception
----
== Resources
* MISRA {cpp}:2008, 5-2-2 - A pointer to a virtual base class shall only be cast to a pointer to a derived class by means of dynamic_cast.
ifdef::env-github,rspecator-view[]
'''
== Comments And Links
(visible only on this page)
=== is duplicated by: S869
endif::env-github,rspecator-view[]