rspec/rules/S3630/cfamily/rule.adoc

70 lines
1.5 KiB
Plaintext
Raw Normal View History

== Why is this an issue?
Because ``++reinterpret_cast++`` does not perform any type safety validations, it is capable of performing dangerous conversions between unrelated types.
Since {cpp}20, a ``++std::bit_cast++`` should be used instead of ``++reinterpret_cast++`` to reinterpret a value as being of a different type of the same length preserving its binary representation, as the behavior of ``++reinterpret_cast++`` is undefined in such case.
This rule raises an issue when ``++reinterpret_cast++`` is used.
=== Noncompliant code example
[source,cpp]
----
class A { public: virtual ~A(){} };
class B : public A { public: void doSomething(){} };
void func(A *a, float f) {
if (B* b = reinterpret_cast<B*>(a)) { // Noncompliant
b->doSomething();
}
int x = *reinterpret_cast<int*>(f); // Noncompliant
}
----
=== Compliant solution
[source,cpp]
----
class A { public: virtual ~A(){} };
class B : public A { public: void doSomething(){} };
void func(A *a, float f) {
if (B* b = dynamic_cast<B*>(a)) {
b->doSomething();
}
int x = std::bit_cast<int>(f);
}
----
include::../see.adoc[]
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
=== Message
Replace "reinterpret_cast" with a safer cast or refactor the code to avoid such an unsafe cast.
=== Highlighting
``++reinterpret_cast++`` keyword
'''
== Comments And Links
(visible only on this page)
include::../comments-and-links.adoc[]
endif::env-github,rspecator-view[]