C++17 introduced std::byte
. It allows you to have byte-oriented access to 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 was
error-prone as the char
type allows you to accidentally perform arithmetic operations. Also, it was 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
}