38 lines
1.2 KiB
Plaintext
38 lines
1.2 KiB
Plaintext
![]() |
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.
|
||
|
|
||
|
`+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
|
||
|
}
|
||
|
----
|
||
|
|