CPP-5126 S3630 Add exceptions and updated description

This commit is contained in:
tomasz-kaminski-sonarsource 2024-06-06 08:39:31 +02:00 committed by GitHub
parent 5dffc88ab6
commit 01b801de64
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -1,10 +1,12 @@
== 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, often leading to undefined behavior.
Because ``++reinterpret_cast++`` does not perform any safety validations, it is capable of dangerous conversions between unrelated types, often leading to undefined behavior.
In some cases, `reinterpret_cast` can be simply replaced by a more focused cast, such as `static_cast`.
If the goal is to access the binary representation of an object, `reinterpret_cast` leads to undefined behavior. Before {cpp}20, the correct way is to use `memcpy` to copy the object's bits. Since {cpp}20, a better option is available: ``++std::bit_cast++`` allows to reinterpret a value as being of a different type of the same length preserving its binary representation (see also S6181).
If the goal is to reinterpret the binary representation of an object as a value of a different type, `reinterpret_cast` leads to undefined behavior.
Before {cpp}20, the correct way is to use `memcpy` to copy the object's bits.
Since {cpp}20, a better option is available: ``++std::bit_cast++`` allows the reinterpretation of a value as being of a different type of the same length, preserving its binary representation (see also S6181).
This rule raises an issue when ``++reinterpret_cast++`` is used.
@ -47,7 +49,13 @@ This rule raises an issue when ``++reinterpret_cast++`` is used.
}
----
=== Exceptions
Since those conversions have a well-defined behavior, this rule does not raise an issue when `reinterpret_cast` is used to convert a pointer to:
* ``++char*++``, ``++unsigned char*++``, ``++std::byte*++`` or `const` variants of these types,
* `std::intptr_t,` `std::unintptr_t`, or another integer type with sufficient size.
include::../see.adoc[]