by a2800276 · 4y ago · 0 comments
1.) Coming from embedded programming, I can see the utility of `std::unreachable`. But shouldn't this be a compiler directive? Or a standardized #pragma? Can someone more knowledgeable in C++ say whether using functions as markers is a common mechanism in std:: ?
2.)Maybe the example is bad here, as it doesn't even save typing. (18 chars for `std::to_underlying` vs. 16 for `static_cast<int>`. The 'old' variant seems more expressive to boot. If anything, how about `static_cast<auto>`? or <underlying> ...
3.) The usefulness of `std::byteswap` to convert data to network byte order seems trivial vs. the venerable old `htonl` family of functions. `std::byteswap` seems more like intrinsics meant to expose possibly present target machine instructions to the user. Like `std::unreachable` this is probably of most use to embedded / low-level programming. This may be a deficiency in the article...
If it's not obvious, I'm not a big C++ fan and read the article with C-tinted glasses :)
From a compiler perspective, using a function makes the most sense, since that fits into the existing control-flow analysis that the compiler will do. Pragmas are processed by the pre-processor, so they aren't appropriate for expressing control flow hints.
2. `std::to_underlying(t)` is a wrapper around `static_cast<std::underlying_type_t<std::remove_cv_t<std::remove_reference_t<decltype(t)>>>>(t)`. So a lot fewer characters. It's also useful since `std::underlying_type_t<T>` behaves weirdly if `T` is not an enum type.
I think you are maybe missing the context that C++ allows the representation of an enum to be defined, e.g. `enum class X : unsigned char {};` vs `enum class Y : unsigned long long {};`. So you can't always cast to `int`. Technically, this isn't the case in C either: the type defaults to `int`, but the compiler will pick a larger type if necessary, e.g. `enum Z { a = ((long long)INT_MAX) + 1 };`
3. `htonl` are not standardized, so they were not part of the C++ standard library. Also, on Windows, I believe you'd need to include `winsock.h` to get access to them, which has its own idiosyncratic issues. You are also missing the context of C++ defining operator overloading, so you can call `std::byteswap(0ull)` and get an `unsigned long long` and you can call `std::byteswap(std::uint16_t{0})` and get a 16 bit unsigned integer.
[0]: https://stackoverflow.com/questions/60802864/emulating-gccs-...
I was questioning the motivation of this to facilitate network-byte-order issues as stated in the blog post. The proposal[1] (that the post linked to) also confirmed that the motivation was to expose more machine code intrinsics rather than deal with network byte order like I expected.
Concerning 1.) yeah, I guess I'd prefer a #pragma aesthetically, but didn't think about the fact that it wouldn't be exposed to the compiler.
Thanks for the well thought out reply!
[1] : https://isocpp.org/files/papers/P1272R4.html#motivation
if you read this and alarm bells didn't ring in your head I really invite you to immediately go check any enum you may have defined in your code because this is absolutely false with MSVC in C++ (https://gcc.godbolt.org/z/6bqW9rE81) (and C is often compiled as C++ on windows)
struct A;
enum B; // as you pointed out, not allowed by the C++ standard
// fine to declare, define, and invoke
void fooA(struct A*);
void fooB(enum B*);
// ok to forward declare, but you can't call them
void barA(struct A);
void barB(enum B);This is wrong a lot of pragmas, I would even say most pragmas are not handled by preprocessor. Some examples: pragma pack, warning control, pragma GCC unroll, per function optimization setting changes, all the pragmas which 1:1 map to c++11 style attributes. None of that is handled by preprocessor, pragma once seems like rare one which is. Yes all of them are compiler specific, but handling compiler specific behavior is one of the main purpose of pragmas.
void foo();
#pragma unreachable
class bar
{
#pragma unreachable
};
namespace foobar {
#pragma unreachable
}
But pragmas can generally be used anywhere, barring tokenization issues. The end result is that `pragma unreachable` would likely end up turning into a magic function call inside the compiler, since it really only makes sense in a spot where you can invoke a function.Also, I think you are conflating pragmas with `__attribute__`, which is how you set per function optimization settings. If you do that with pragmas, then it isn't limited to a single function.
This seems par for the course for all C++ stuff: it's designed from a compiler perspective, not from a programmer perspective.
The correct way, IMHO, is to design features that supports the user's workflow, not to design the same feature in a way to make the compiler's job easier.
> `htonl` are not standardized, so they were not part of the C++ standard library.
They're POSIX standardised. The decision should have been to adopt something that exists in an existing and widespread standard rather than the worrisome not-invented-here syndrome that I see here.
They are: https://pubs.opengroup.org/onlinepubs/9699919799/functions/h...
I don't thing this is remotely true. C++ pragmas were designed with the express purpose of providing additional information to compilers.
I'm not so sure attributes are better. They have political traction, but that does not mean better. All major compilers use pragmas effectively to implement custom compiler flags. See for instance how Visual C++ uses pragmas extensively to toggle specific compiler warnings, not to mention the infamous #pragma once
I can believe this is useful in explicitly-typed form, i.e. using std::byteswap<T> with T specified. But letting T be inferred seems quite dangerous: C++ loves changing integer types around all by itself (via type promotion, for example), and byteswap<int> and byteswap<long> are (on UNIXy systems) simply not the same operation. For that matter, byteswap should really only be used on uintN_t.
byteswap(a+b) is just asking for trouble.
They are still far from being the only game in town.
1. Why "should" it be something different? It is semantically part of code flow; making it a pragma breaks that model. This replaces the nonstandard __builtin_unreachable().
2. This doesn't exist to save typing. static_cast<auto> doesn't make sense to me (that reads like a no-op). static_cast<underlying> introduces a new reserved word which is a big no-no.
3. This is not the same as htonl, which only does anything on little-endian machines. (htonl is also a POSIX function, not a C++ function.)
In practice what is actually available and whether it works satisfactorily varies considerably more than for the hosted environments. Almost everything is up for grabs and so you probably can't rely on the standard much. Your compiler vendor probably couldn't care less what the standard says anyway.
Probably "committee pragmatism", a stdlib change might be easier to get approved than a language change, and compilers already have builtins for this, they're just not compatible (but the differences can be wrapped in a macro, and since C++ doesn't like to expose macros, it's probably still a macro, but hidden inside a stdlib template).
FWIW it looks like C23 will also just get a macro:
https://thephd.dev/ever-closer-c23-improvements#unreachable-...
Another way of thinking of this: With NDEBUG undefined, the sequence `assert(condition); if(!condition) action();` is perfectly reasonable and equivalent to the naked assert. But, because assert(false) is defined, defining NDEBUG changes the semantics of the code, with the two examples having identical behavior when NDEBUG is unset, and different behavior when NDEBUG is set. This is contrary to my understanding of the intent of NDEBUG, to suppress debugging information without changing semantics.
A third view: With NDEBUG undefined (which is normal for test and development), /I have no way of testing what happens past an assert(false)/. If I then define NDEBUG for a release build, I'm by definition exposing my user to untested code. The compiler might (with a defined assert(false)) define the behavior of this new code, /but I cannot, since I can't test it./ It just makes more sense to acknowledge that anything past an event horizon is undefinable, and call it undefined.
2.) static_cast<int> is shorter, if you know that the underlying type is int. But even if you know, you might not want to spell out int, to be more robust to code changes, which might involve a change of the underlying type of the corresponding enum.
In generic context you might not even know the underlying type.
3.) I absolutely agree. I think it was a mistake to include. The included `std::byteswap` can be expressed in terms of `std::ranges::reverse(std::as_writable_bytes(obj))`. It could be quality of implementation detail to get a bswap instruction from the latter.
I would be happy with equivalents of the `htonl` functions in the standard library, but I have strong opinions of the appropriate function signatures of it for C++.
The issue is exactly which code pattern is detected by which compiler varies a lot, so to avoid having to rely on that there was a strong push to add all these explicit intrinsics. Also std::bytesewap is more readable than the longer reverse+as_writeable_bytes.
byteswap semantically works on the object representation of the integer, while all other operations semantically work on the integer value, expressed in powers of two.
The C++ language has no strong requirements on the object representation of the underlying integer. The C++20 guarantee of two's complement also only just expressed in terms of integer value, not bit representation.
Therefor `byteswap` somewhat sticks out. It's possibly useful for `std::endian::little == std::endian::native` or `std::endian::big == std::endian::native`, and for `std::has_unique_object_representations_v<T> == true` (aka. no padding bits) for the corresponding integral type T. CHAR_BITS also change the semantics.
So, in this sense it is quite low level, and you have to check all of these to make use of it, or you have to implicitly rely on implementation defined values of these for the targets you care about.
I'm not saying that byteswap is not useful though. But it has the wrong interface. It reverses sequence of bytes, it does not work on integers.
edit:
Oh, in addition of having no padding bits, you also want no trap representations. I don't know if you can check for that.
edit2:
Apparently, you don't necessarily need to check for padding bits, byteswap does it for you, and fails to compile if there are padding bits:
https://eel.is/c++draft/bit#byteswap-2
I don't see trap representations being handled at all. This might be a defect.
> In generic context you might not even know the underlying type.
Thanks for pointing this out! I'm aware that the underlying type of an enum isn't always `int`. This is what I meant by saying the `static_cast` feels more expressive to me, i.e. reading the code, at least I'll now on sight what type is being used here. I'd probably have to 'let go' more to effectively use CPP, but this category of mechanism to cope with a generic/type system so complicated that I can't figure out the type of anything anymore. In the same vein, 'making code more robust to changes' feels like kicking the can down the road (to me). At some point you'll need to deal with the actual type ...
Lisp perspective: anything that can be a function almost certainly should be a function (and not a special operator or macro).
std::unreachable() does not have any arguments; therefore it doesn't need any special argument evaluation semantics that would require a compiler built-in.
The way C and C++ work, compiler directives are keywords and not identifiers. Keywords are not namespaced. Introducing a keyword called "unreachable" is problematic; far more so than a new element in the std namespace.
My only problem with std::unreachable is that I would never use it over std::abort.
Nobody needs a function whose only job is to invoke undefined behavior (from which it is then assumed that it is not reached).
It's a good cold day, so I can almost hear the Rust people laughing in the distance.
The only difference is that it’s marked unsafe.
https://doc.rust-lang.org/std/hint/fn.unreachable_unchecked....
There is a safe version that is just a wrapper around panic! with a standardized message.
Again, I'm not up on the latest papers, but that was the situation last I checked.
auto x = (y == 1) ? foo :
(y == 2) ? bar :
...
std::unreadchable();std::unreachable() goes a step further, and tells the compiler that it doesn't even have to emit the call instructions or any instructions leading up to it.
But I don't see a reason why this is not be possible with an attribute? (I realize this is a purely aesthetic call from me .. a function that doesn't actually get called seems out of place). My guess would be that using a function allows niche compilers that don't support attributes to support `unreachable` and is easy to implement for compilers already using __builtin
That's not what I or the person I was replying to was saying, and wasn't the relevant point.
We were saying how else could you give the compiler an intrinsic, without a call of some kind? Like what other syntactic mechanism is there you can treat as an intrinsic in the compiler.
The alternative would be a new keyword, but then the go-to complaint would just be about c++ keyword bloat and source compat regressions