rspec/rules/S6022/rule.adoc

40 lines
1.3 KiB
Plaintext
Raw Normal View History

2021-01-27 13:42:22 +01:00
{cpp}17 introduced std::byte. It allows you to have byte-oriented access to a memory in a type-safe unambiguous manner. Before, you had to use either ``++char++``, ``++signed char++``, or ``++unsigned char++`` to access memory as bytes. The previous approach is error-prone as ``++char++`` type allows you to accidentally perform arithmetic operations. Also, it is confusing since ``++char++``, ``++signed char++``, and ``++unsigned char++`` are also used to represent actual characters and arithmetic values.
2021-02-02 15:02:10 +01:00
2021-01-27 13:42:22 +01:00
``++std::byte++`` is simply a scoped enumeration with bit-wise operators and a helper function ``++to_integer<T>++`` to convert byte object to integral type T.
2021-02-02 15:02:10 +01:00
2021-01-27 13:42:22 +01:00
This rule will detect byte-like usage of ``++char++``, ``++signed char++``, and ``++unsigned char++`` and suggest replacing them by ``++std::byte++``.
== Noncompliant Code Example
----
void handleFirstByte(char* byte);
void f(int* i) {
char* c = reinterpret_cast<char*>(i); // Noncompliant
handleFirstByte(c);
}
unsigned char negate(unsigned char byte) {
return ~byte; // Noncompliant
}
----
== Compliant Solution
----
void handleFirstByte(std::byte* byte);
void f(int* i) {
std::byte* byte = reinterpret_cast<std::byte*>(i); // Compliant
handleFirstByte(byte);
}
std::byte negate(std::byte byte) {
return ~byte; // Compliant
}
----