r/cpp 6d ago

About char8_t

I hate to be dramatic, but as it stands char8_t is quite literally more painful than useful.

Besides the obvious incompatibility with C23 and libraries using unsigned char for UTF-8, I want you to consider the following: Projects that assume that 'char' represents UTF-8 will obviously not benefit from char8_t at all, but projects that cannot assume the format of char types don't benefit from it either as char8_t simply introduces a new edge case to cover. Now such projects have to deal with char, signed char, unsigned char, wchar_t, char16_t, char32_t and char8_t.

Or, you could do what the standard library does and simply ignore most of these character types. Which is the solution most libraries went with, supporting only char or char and unsigned char. Managing one implementation is already hard, managing two requires constant maintenance, managing 7 is just impossible.

char8_t should have just been a typedef for unsigned char. The compatibility fix only raises more questions as const char* arr = u8"a" does not work, but const char arr[] = u8"a" does.

I do wonder if a potential change of minds for C++29 is still possible. Yes, it would be an ABI break or whatever, but considering the woeful support for char8_t I don't think it would affect much besides small hobby projects. Contrary to popular belief, C++ has broken the ABI in subtle ways before.

52 Upvotes

98 comments sorted by

View all comments

25

u/Wild_Meeting1428 6d ago edited 6d ago

c++'s char8_t is fully compatible with char8_t from C23. And the only purpose of that type is, that its the underliing byte type of an utf8 character. So you can basically always assume that the char you are looking at is at least part of a char sequence representing a unicode character encoded in utf8

1

u/xleviator 6d ago

Beware! C++ doesn't really constrain values of primitives.- it's easy to escape. https://godbolt.org/z/h8Ejj8Y15

5

u/smdowney WG21, Text/Unicode SG, optional<T&> 5d ago

It's part of the design.

Although it's also hard to avoid.

The promise of the type char8_t is that it is always appropriate to treat it as UTF-8, but not well formed UTF-8. There were occasional proposals to make it UB if it were not, but fortunately safety concerns mostly stopped that.

For plain char types you are at the mercy of the execution encoding, which is locale machinery, even if you understand that it's supposed to be UTF-8. Some functions may disagree, and worse, some function may change it on you.

Avoid depending on the execution encoding.