reinterpret_cast 在 char* 和 std::byte* 之间

reinterpret_cast between char* and std::byte*

我正在阅读 type aliasing rules 但无法确定此代码中是否包含 UB:

std::vector<std::byte> vec = {std::byte{'a'}, std::byte{'b'}};
auto sv = std::string_view(reinterpret_cast<char*>(vec.data()), vec.size());
std::cout << sv << '\n';

我很确定它不会,但我经常对 C++ 感到惊讶。 reinterpret_castchar*unsigned char*std::byte* 之间总是允许的吗?

此外,添加 const 是否合法,例如:

std::array<char, 2> arr = {'a', 'b'};
auto* p = reinterpret_cast<const std::byte*>(arr.data());

同样,我怀疑它是合法的,因为它说

AliasedType is the (possibly cv-qualified) signed or unsigned variant of DynamicType

但我想用 reinterpret_cast 确保一劳永逸。

代码没问题

标准允许

char*std::byte* 别名任何指针类型。 (小心,因为反过来是不正确的)。

([basic.types]/2):

For any object (other than a base-class subobject) of trivially copyable type T, whether or not the object holds a valid value of type T, the underlying bytes ([intro.memory]) making up the object can be copied into an array of char, unsigned char, or std​::​byte ([cstddef.syn]).43 If the content of that array is copied back into the object, the object shall subsequently hold its original value.

([basic.lval]/8.8):

If a program attempts to access the stored value of an object through a glvalue of other than one of the following types the behavior is undefined:

  • a char, unsigned char, or std​::​byte type.

是的,您可以添加 const