In C++, which types may read the bytes of any object without breaking strict aliasing, and why does that exception not work in reverse?
answer
- the three character-like types
- signed char is not on the list
- inspect bytes, not invent objects
- a char buffer holds char objects
- memcpy out of the buffer
basics
~20 schar, unsigned char and std::byte may access the bytes of any object. The exception is one-way: a char buffer still holds char objects, so reading it through a float or struct pointer is undefined. Copy the bytes out with std::memcpy.
solid answer
~50 sThe strict aliasing rule lists `char`, `unsigned char` and `std::byte` (C++17) as types through which the stored value of **any** object may be accessed. That is what lets `std::memcpy`, hashing, serialisation and hex dumps examine an object's **object representation**. `signed char` is not on the C++ list, unlike in C. The exception only covers the direction *character type looks at object*. A `char` array received from a socket or a file holds `char` objects; reading it through a `float*` or `Header*` accesses `char` objects through a glvalue that is neither their type nor a character type, so it is undefined behaviour. To get a typed value out of raw bytes, copy them into a real object with `std::memcpy` (or `std::bit_cast` for a same-size array), which both compile to plain loads when the size is small and known.
code
cpp · 24 lines#include <cstddef>
#include <cstdio>
#include <cstring>
// Allowed: unsigned char (or char, or std::byte) may read the bytes of any object.
void dump(const void* p, std::size_t n) {
const auto* bytes = static_cast<const unsigned char*>(p);
for (std::size_t i = 0; i < n; ++i) std::printf("%02x ", bytes[i]);
std::printf("\n");
}
int main() {
float f = 1.0f;
dump(&f, sizeof f); // prints the object representation
const auto* b = reinterpret_cast<const std::byte*>(&f); // std::byte: also allowed (C++17)
std::printf("top byte %02x\n", std::to_integer<unsigned>(b[3]));
alignas(float) char wire[sizeof(float)] = {0, 0, '\x80', '\x3f'};
// float g = *reinterpret_cast<float*>(wire); // UB: the exception is one-way
float g;
std::memcpy(&g, wire, sizeof g); // defined: copies the bytes into a float
std::printf("%g\n", g);
}go deeper
Recall that char, unsigned char and std::byte may look at the bytes of any object, which is how memcpy and hex dumps work.
Explain the exact list, why signed char and uint8_t are not safe bets, and why reading a char buffer through a struct pointer is still undefined.
Spot in-place parsing of byte buffers in review and replace it with memcpy-based readers, knowing what C++20 implicit object creation does not rescue.
Standardise one byte type and one deserialisation helper across the codebase so raw-memory code is easy to audit and never depends on aliasing subtleties.
## The exception in the rule C++'s aliasing rule ([basic.lval]) allows an object of dynamic type `T` to be accessed through a glvalue of: - `T` or a type similar to it; - the signed or unsigned type corresponding to `T`; - **`char`, `unsigned char` or `std::byte`**. The last bullet is the exception every byte-level routine depends on. It lets code treat any object as a sequence of bytes and read its **object representation**: the `sizeof(T)` bytes that hold its value, padding included. `std::byte`, introduced in C++17 in `<cstddef>`, exists for exactly this: a byte type that supports bitwise operations but no arithmetic, so it cannot be confused with a character or a small integer. Two details trip candidates up: - **`signed char` is not on the list.** C allows all character types; C++ names only `char`, `unsigned char` and `std::byte`. Use `unsigned char` or `std::byte` for byte inspection. - **`std::uint8_t` is not guaranteed to be on the list.** It is usually an alias for `unsigned char`, but the standard does not require it to be a character type, so portable byte code spells `unsigned char` or `std::byte`. ## Why the exception is one-way The rule is phrased in terms of the object that is really there. Reading a `float` through `unsigned char` is fine because the object is a `float` and the glvalue type is a character type. Turn it around. A buffer declared `char buf[1500]` and filled by a socket read holds 1500 `char` objects. `*reinterpret_cast<float*>(buf)` accesses one of those `char` objects through a `float` glvalue. `float` is not `char`, not its signed or unsigned counterpart, and not a character type, so the access is **undefined behaviour**. The bytes may look exactly like a `float`, but no `float` object lives there. (Alignment is a second, separate problem: a `char` array has alignment 1.) | Direction | Example | Status | |---|---|---| | bytes of an object, read as `unsigned char` | hex-dumping a `double` | defined | | bytes of an object, read as `std::byte` | hashing a key's representation | defined | | bytes of an object, read as `signed char` | same, with `signed char*` | undefined in C++ | | `char` buffer read as `float` or a struct | parsing a packet in place | undefined | | `char` buffer copied into a `float` with `memcpy` | parsing a packet by copy | defined | ## Reading versus writing through the exception Access in the aliasing rule means reading or modifying, so the exception covers writes too. `std::memset(&obj, 0, sizeof obj)` and byte-by-byte copies into an object are allowed. The constraint is on what you write: if the bytes do not form a valid value of the object's type, a later read as that type has undefined behaviour. For unsigned integer types every bit pattern is a valid value; for `bool`, or a class with invariants, it is not. ## Getting typed values out of bytes The portable pattern copies the bytes into an object of the target type: 1. declare the object: `float g;` 2. copy: `std::memcpy(&g, buf + offset, sizeof g);` 3. use `g`, converting byte order if the source was big-endian. `std::memcpy` copies object representations and is specified to work between trivially copyable objects. Compilers inline a small constant-size `memcpy` into ordinary loads, so this is as fast as the cast. In C++20, `std::bit_cast<float>(arr)` does the same from a `std::array<unsigned char, 4>` or an `unsigned char[4]` array of matching size. ## What C++20 implicit object creation does and does not change C++20 added **implicit object creation**: some operations, including `std::malloc`, `operator new`, `std::memcpy` and beginning the lifetime of an `unsigned char` or `std::byte` array, may implicitly create objects of implicit-lifetime types when that gives the program defined behaviour. It narrows the gap for storage allocated as `unsigned char` or `std::byte`, but it does not apply to a plain `char` array, and it never fixes a misaligned address. Relying on it in parsing code means arguing about lifetime rules in every review; copying the bytes out does not. ## Interview checklist - List the three types exactly: `char`, `unsigned char`, `std::byte`. - State that the exception lets bytes be read, not objects be conjured. - Explain the reverse case with a buffer and a struct. - Offer `std::memcpy` or `std::bit_cast` as the fix.
- Why is std::byte preferable to unsigned char for raw memory?Both may alias any object. `std::byte` (C++17) is a distinct enumeration type that supports only bitwise operators and `std::to_integer`, so it cannot be accidentally added, printed as a character or promoted into arithmetic. It states intent: this is memory, not a number or a letter. `unsigned char` remains the right choice when you interoperate with C APIs.
- May you write to an object through an unsigned char pointer?Yes, access in the aliasing rule covers both reading and modifying, so `std::memset` and byte-wise copies are allowed. What you must not do is write bytes that are not a valid value representation of the object's type and then read it as that type; for the unsigned integer types every bit pattern is valid, for `bool` it is not.
A photocopier may copy any document, but a pile of loose copies is not a bound book you can lend out: to get a book back, you bind the pages into a new one, which is what copying bytes into a real object does.
- Any character type, including signed char, may alias any object in C++.
- Because char may alias anything, a char buffer may be read through any pointer type.
- std::uint8_t is guaranteed to have the same aliasing exception as unsigned char.
- std::byte is just a typedef for unsigned char.
- The exception only allows reading, never writing, the bytes.