rspec/rules/S6022/rule.adoc

38 lines
1.2 KiB
Plaintext
Raw Normal View History

2020-12-23 14:59:06 +01:00
C++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.
2020-12-23 14:59:06 +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.
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
}
----