rspec/rules/S5302/cfamily/rule.adoc

51 lines
1.1 KiB
Plaintext
Raw Normal View History

== Why is this an issue?
2021-04-28 16:49:39 +02:00
Casting from a virtual base to a derived class, using any means other than dynamic_cast has undefined behaviour. The behaviour for dynamic_cast is defined.
Note: As of {cpp}17, the program is considered as ill-formed and an error is reported.
Most compilers emit an error for previous versions of {cpp} as well.
=== Noncompliant code example
2021-04-28 16:49:39 +02:00
2022-02-04 17:28:24 +01:00
[source,cpp]
2021-04-28 16:49:39 +02:00
----
class B { ... };
class D: public virtual B { ... };
D d;
B *pB = &d;
D *pD1 = ( D * ) pB; // Noncompliant - undefined behaviour
D *pD2 = static_cast<D*>(pB); // Noncompliant - undefined behaviour
----
=== Compliant solution
2021-04-28 16:49:39 +02:00
2022-02-04 17:28:24 +01:00
[source,cpp]
2021-04-28 16:49:39 +02:00
----
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
2021-04-28 16:49:39 +02:00
* 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)
include::comments-and-links.adoc[]
endif::env-github,rspecator-view[]