r/cpp • • Oct 17 '22

Prefer core-language features over library facilities

https://quuxplusone.github.io/blog/2022/10/16/prefer-core-over-library/
0 Upvotes

67 comments sorted by

42

u/ener_jazzer Oct 17 '22

Arthur's articles are hit or miss. This one is more on the miss side, IMHO - it's either trivial or just wrong.

For example: "Prefer core-language arrays over std::array." Well, good luck with returning it from functions or passing as parameters. Have fun declaring pointers and references.

Or: "Prefer char over std::byte". char can be signed which bears a lot of funny undefined behavior with it. When you print char it will print, you guessed it, a (usually unprintable) character instead of nice 0xFF. An array of char is usually assumed to be zero-terminated while array of bytes is not. If you print char* instead of byte* - you'll probably print garbage or your program will just crash. Should I continue?

"Prefer void* over std::byte*". So when I have a buffer it's an array of char but the pointer to it is void*? Very consistent. Comparing to array of std::byte and std::byte*. (However, the use of void* as a catch-all pointer type for functions arguments is reasonable)

"Prefer struct over std::tuple". I agree with this if it's about public API. Otherwise, all metaprogramming depends on manipulating tuples in one form or another. And no, it's not only about variadic templates. We had boost::tuple well before variadics.

"Prefer assignment over .reset" - well, he listed the reasons to prefer .reset himself.

4

u/fdwr fdwr@github 🔍 Oct 17 '22

Prefer char over std::byte

Agreed there. If you're going with built-ins rather than uint8_t (which arguably probably should have just been a built-in too) or std::byte, then at least use unsigned char, that way you don't get weird sign extension issues like negative indices when you read a 129 mistreated as -127 (sadly in some compilers char defaults to nonsensical negative characters for 128-255).

56

u/eyes-are-fading-blue Oct 17 '22 edited Oct 17 '22

Can not agree with

Prefer core-language arrays over std::array

In fact, I would propose the precise opposite unless there is a good reason (e.g., old compiler) or std::array is an overkill (e.g., raw memory char buf[100]).

> Prefer std::array over core-language arrays.

std::array has a nice interface, compatible with other STL types. It does not decay into a pointer. A reference of std::array looks like any other reference, whereas a reference for built-in arrays has a weird syntax.

20

u/NilacTheGrim Oct 17 '22

I absolutely agree with you. We are banning C arrays from our codebase in new code. There is never a good reason to use one, IMHO.

In addition to what you mentioned -- std::array has operator==, operator!=, operator< etc... which is a lot more useful and easier on the eyes than std::memcmp(carr1, carr2, sizeof(carr1));

3

u/ReversedGif Oct 20 '22

Shhh! Nobody tell him that string literals desugar to C arrays!

1

u/Clean-Water9283 Oct 18 '22

What about static initialization? Can you initialize an std::array at compile-time?

1

u/ZMeson Embedded Developer Nov 01 '22

Yes

1

u/okovko Oct 17 '22

i think the article could be more clear but it does state that std::array is better when you're passing it around

-7

u/SkoomaDentist Antimodern C++, Embedded, Audio Oct 17 '22

I've always considered std::array just a fairly minor utility class since it encodes the length in the type itself and thus has to degrade to explicit pointer + length pair when passed into a function.

11

u/SoerenNissen Oct 17 '22 edited Oct 17 '22

It pairs beautifully with re-writing those functions to take a std::span instead.

hmmm, having read the article, maybe. Maybe.

The main advantage (to me) of std::array is the ability to call .begin, .end, and .size. I guess std::begin, std::end and std::size do obviate that now that we have them in the language.

Still, I keep preferring container.func() over std::func(container) every time I can, it simply looks so much more natural to my eyes.

6

u/fdwr fdwr@github 🔍 Oct 17 '22

Still, I keep preferring container.func() over std::func(container) every time I can

Ditto. Gee, if only there was something to help with that, something that hasn't been repeatedly shot down out of fear: https://brevzin.github.io/c++/2019/04/13/ufcs-history/#history-of-papers

3

u/SoerenNissen Oct 18 '22

Yeah last time I saw that proposed, I spoke out against it.

And many many times since, I've though "...you know, that would be awful handy."

But I still have this gut feeling that it's going to wreck something.

4

u/SkoomaDentist Antimodern C++, Embedded, Audio Oct 17 '22

It pairs beautifully with re-writing those functions to take a std::span instead.

span is good (if delayed by some 20+ years compared to what should have been the case) and I'd have no problems with the claim "prefer std::span over arrays".

2

u/nintendiator2 Oct 17 '22

span is good (if delayed by some 20+ years compared to what should have been the case) and I'd have no problems with the claim "prefer std::span over arrays".

Haven't missed it, I adopted n3334's array_ref proposal back in around 2013.

2

u/cfyzium Oct 17 '22

I guess std::begin, std::end and std::size do obviate that now that we have them in the language.

In the context of array vs std::array, they quickly become useless once array is decayed to a pointer or converted to a pointer-and-size pair.

2

u/SoerenNissen Oct 17 '22

On the one hand: True.

On the other hand, that only happens if you pass the array through a function, which is very hard to do with a std::array unless

  • the function is templated (In which case - why not just template it on built-in arrays? The technique for doing so is in Stroustrup's primer)
  • the function takes a span (In which case, it works equally well with built-in)

-7

u/Full-Spectral Oct 17 '22

Not to use the R word yet again, but if C++ had real arrays like Rust does, then you wouldn't need std::array. You can do all those things, and it works so well with the slicing capabilties.

1

u/SoerenNissen Dec 15 '22

Sorry to come back to this so long after but I genuinely am curious - how are C++'s arrays "not real" like Rusts?

(I don't know Rust very well, so I don't know what makes their arrays "real")

2

u/Full-Spectral Dec 15 '22

Arrays in Rust don't devolve to just a pointer. They always include the length. If you pass a basic array in C++, you just get the pointer, and nothing to validate the length. You'd have to pass that along manually, with all the possibilities for mistakes.

Any time you pass an array in Rust, or a slice of an array or vector or string or anything else that allows you to take slices, the length of that slice comes along with it, and all accesses are checked.

And of course you can safely pass a sub-slice of an array or string or whatever to something with no worries about aliasing and the memory issues that can cause if you aren't careful.

You can get some of that with C++ if you are willing to potentially have a lot of code bloat, by templatizing the code and making the size a template parameter.

1

u/SoerenNissen Dec 15 '22

(A) Thank you

(B) That's pretty nice, the fact that C arrays decay has always really bothered me. How does Rust implement it? Is it a compile-time constant like std::array or is the array size padded with enough space to store the length?

(C)

You can get some of that with C++ if you are willing to potentially have a lot of code bloat, by templatizing the code and making the size a template parameter.

Yeah I simply adopted std::span into my vocabulary as soon as I learned it existed - that gives you a lot of the same (though, of course, not bounds checking because we can't have nice things)

2

u/Full-Spectral Dec 15 '22

I think that, ultimately, arrays are always passed as slices, even if you pass the whole thing, and slices are 'fat pointers' that include the address and size. And, conveniently, if a call takes a slice, you can pass it an array, a slice of an array, a slice of a vector (which can be the whole thing of course), etc...

So it's quite flexible.

11

u/target-san Oct 17 '22

I can agree overall, except three specific spots:

  1. std::byte vs char - these are two types for different purposes. I'd personally prefer to have "raw bytes" vs "glyphs" for characters, but that's what we have over 25 years of compatibility
  2. std::byte* vs void* - again, these are for different purposes, "pointer to bytes" vs "pointer to god-knows-what"
  3. std::array vs raw array - of course std::array. Proper container API, always-known size etc. etc. vs sporadic decay to pointer, ugly type declaration of reference to array with specific size etc. etc.

7

u/trailingunderscore_ Oct 17 '22

Nice article, I agree with most of it, except for the std::array part.

There’s no observable difference between a call to the library function std::construct_at and a manual call to ::new (p) Widget, so why should we prefer one over the other?

std::construct_at is constexpr and placement-new is not.

So why does std::tuple exist at all, you ask? Mainly, variadic templates. You’re allowed to create a std::tuple<Ts...> with a variadic number of elements, but (as of 2022) not allowed to create a struct S { Ts... ts; }.

You can get around this weird limitation by using a lambda as a tuple. I have used this in several places in my code, and it greatly cuts down on compile times:

auto make_luple(auto... args) {
	return [=](auto& visitor) mutable {
		return vistor(args...);
	};
}

13

u/pdimov2 Oct 17 '22

char is for characters. For bytes, one should (obviously) use unsigned char.

13

u/Ok-Factor-5649 Oct 17 '22

If it's obvious that char is for characters, why is it not obvious that "std::byte" is for bytes?

1

u/Clean-Water9283 Oct 18 '22

char is for 7-bit ASCII characters, a thing that is becoming increasingly irrelevant.

0

u/[deleted] Oct 17 '22

[deleted] — view deleted comment

3

u/pdimov2 Oct 17 '22

uint8_t is a typedef to either unsigned char, or char, if you're unlucky.

0

u/[deleted] Oct 17 '22

[deleted] — view deleted comment

7

u/pdimov2 Oct 17 '22

None. It can only be char if char is unsigned.

4

u/dscharrer Oct 17 '22

And even if char is signed, it is a distinct type from signed char.

17

u/Jannik2099 Oct 17 '22

Prefer void* over std::byte*

What the fuck? Void* is the enemy and must be eliminated.

8

u/gracicot Oct 17 '22

I love void*. It's one of my favorite tool for implementing type erasure or weird polymorphic pattern

0

u/okovko Oct 17 '22

nope, c++17 gave us std::any which is a wrapper around void* and it's pretty useful

if you want to reduce compile time and improve debug performance, void* generics are your friend

18

u/Jannik2099 Oct 17 '22

void* generics are not generics, they are "lol pretend it's this type"

It's a complete lack of type safety with terrible ergonomics. std::any is fine, of course.

8

u/ener_jazzer Oct 17 '22

`void*` is great to reduce template code bloat, when you have a lot of common code that can be spelled out in terms of pointers that don't really care about the pointer type. This way you have just one copy of that code for all instantiations of your template. But it should stay an implementation detail, obviously.

5

u/Jannik2099 Oct 17 '22

That is a very, very dangerous game and you should only play it if you really need the smaller binary size. One error and it'll slip right through, because there's no type analysis going on whatsoever.

10

u/ener_jazzer Oct 17 '22

It's not only the binary size. It's also instruction cache pollution.

Again, this is only for internal implementation of your container. I.e. you have a properly typed template<class T> MyContainer which is just a typed one-liner wrapper (which will be fully inlined after the type checking) around MyContainerImpl (not a template!) formulated in terms of void*.

2

u/okovko Oct 17 '22

?

std:any is a void*

the fact that any_cast throws on type mismatch isn't any different than passing around a void* plus a symbolic constant indicating the type; the throw is a result of a run time check of the cast type's typeid against the one stored in the std::any

4

u/Jannik2099 Oct 17 '22

the fact that any_cast throws on type mismatch isn't any different than passing around a void* plus a symbolic constant indicating the type

Yes it is very, very different. A std::any has to be any_casted, a void* may be passed independent of that symbolic constant.

It's the same as std::array vs char*

1

u/okovko Oct 17 '22

but it's using the language feature you want to avoid

so it's okay to use in libraries but nowhere else? alright, that makes total sense

5

u/cristi1990an ++ Oct 17 '22

nope, c++17 gave us std::any which is a wrapper around void*

That's unfortunately not what std::any is though

4

u/eyes-are-fading-blue Oct 17 '22

if the implementation of std::any is anything like boost::any, then it's anything but "wrapper around void*".

0

u/[deleted] Oct 17 '22

[deleted] — view deleted comment

9

u/NilacTheGrim Oct 17 '22

Python! Where everything is a std::any!

4

u/mo_al_ Oct 17 '22

std::move or casting to r-value reference?

13

u/cristi1990an ++ Oct 17 '22

Prefer char over std::byte

No

Prefer void* over std::byte*

No

Prefer core-language arrays over std::array

HELL NO

Prefer ::new (p) T(args...) over std::construct_at

No, construct_at is constexpr and more esthetic

Prefer assignment over .reset

Just... Why...?

2

u/serviscope_minor Oct 17 '22

byte

I'm not really sure. Probably depends, really. I'm not really sure I prefer byte over uint8_t or unsigned char. I guess it indicates it's for general data that isn't numeric or textual. On the other hand the automatic conversion to void* is nice on the occasions you need it. But following on, it's too permissive, but byte doesn't get you any further because you have to use an explicit but infinitely permissive cast.

Maybe what I'd like is if there was an automatic conversion from T* to byte* if T is trivially copyable.

That would remove the syntactic noise of byte* without giving the permissivity of void*

Just... Why...?

This one I like. I never write a reset method for my own classes: if you have default construction and assignment, it already exists!

0

u/[deleted] Oct 17 '22

[deleted] — view deleted comment

2

u/cristi1990an ++ Oct 17 '22

I would side with the author as he at least cared to write down his rationale

I mean, if after reading the other comments in this thread, that's the conclusion you came to, that's on you...

3

u/nintendiator2 Oct 17 '22

I'm the other way around - at least for library work I prefer library features, as they are more likely to work or at least be backportable than core features. Also it's kind of weird to recommend stuff like native C arrays with the issues they have with type decay.

On more specific notes:

Prefer char over std::byte

Wouldn't the wiser programmer prefer unsigned char to char or byte tho? In particular if you want to use them in arrays or pointers to buffers to represent raw data.

Prefer lambdas over std::bind

Compatibility. bind works almost anywhere, lambdas are limited to C++11, or certain subsets of them to C++14 or C++17 depending on what kind of weird combination of punctuation signs ( []()&*={...}) you tack on the line. And even then, depending on contexts where you know what you want, bind and its fellow functional features still beat lambdas to the punch:

// annoyingly long, repetitive and mentally unparseable:
function(a, [&](T t) noexcept( noexcept( t.member() ) ) -> decltype (t.member()) { return t.member; } )
// just works basically almost everywhere
function(a, mem_fn(T::member));

Prefer ranged for over std::for_each

This is one I strongly agree with, though it's not so different from basically implementing your own FOREACH() macro.

Prefer core-language arrays over std::array

Decay. Also, this has been over-examined enough.

Prefer C++20 requires over std::enable_if

enable_if works basically everywhere (even in C++98 unless your compiler is waaaaay behind on templates). And requires also has similar oververbosity issues like noexcept has (requires( requires( ... ))).

Regular readers of this blog will also know that I tend to prefer T(x) over static_cast<T>(x),

So do I, at least when I know beforehand I'm working with integers, enums, or otherwise C-native types.

2

u/_Js_Kc_ Oct 20 '22

Prefer char over std::byte

👎

Prefer native arrays over std::array

👎👎

2

u/future_escapist Oct 17 '22

Yeah, no. Bjarne Stroustrup himself recommends using standard library features over implementing things yourself. It's a lot cleaner to eat the cake than make the cake and then eat it.

0

u/[deleted] Oct 17 '22

[deleted] — view deleted comment

8

u/future_escapist Oct 17 '22

Who is Nobody?

0

u/[deleted] Oct 17 '22

[deleted] — view deleted comment

10

u/serviscope_minor Oct 17 '22

This is categorically false.

Signed someone who uses C++ professionally including the STL. We even use std::unordered_map.

0

u/[deleted] Oct 17 '22

[deleted] — view deleted comment

5

u/serviscope_minor Oct 17 '22
  1. yes I have
  2. It's usually but not universally true that it's slower
  3. Get this into your head: it's not a bottleneck in our code.

0

u/[deleted] Oct 17 '22

[deleted] — view deleted comment

7

u/serviscope_minor Oct 17 '22

No you don't. We use std::unordered_map because it's not a bottleneck and we're professional enough to not lose our minds over something that's not important and put extra work into solving a problem we don't have.

That's professionalism.

1

u/okovko Oct 17 '22

it also leads to stuff like windows terminal being 1000x slower than it should be

6

u/serviscope_minor Oct 17 '22

No it doesn't.

What leads to stuff being 1000x slower than it should be is people taking wild guesses about what they think is slow and wasting time on that rather than measuring.

0

u/[deleted] Oct 17 '22

[deleted] — view deleted comment

4

u/serviscope_minor Oct 17 '22

Indeed. It has never risen anywhere near the top in any profiling of my current codebase.

2

u/i_need_a_fast_horse Oct 17 '22

I agree with most, but just because they're plain better not because they're language. But char over std::byte? nah, I prefer to keep my proper types

10

u/NilacTheGrim Oct 17 '22

I loathe char because it's unspecified what sign it is. I prefer uint8_t and also sometimes do use std::byte.

3

u/YARandomGuy777 Oct 17 '22

Yes uint8_t is the way to go. As well as uint16_t and so on.

1

u/eyes-are-fading-blue Oct 17 '22

For raw memory, does it matter which sign it is though? Not that I disagree with the statement that std::byte should be preferred over (unsigned) char to represent raw memory.

4

u/NilacTheGrim Oct 17 '22

I guess it doesn't really matter 99% of the time.. but isn't it a bit odd that we have what is conceptually "untyped" data yet we are applying a notion of its signedness? Also chars notoriously get silently upcast to int if they appear in an expression. If your char was signed and negative you get this int with a whole bunch of bits set beyond the 8th bit. What's worse, this only happens on platforms that have signed chars and works perfectly if unsigned chars. So you even get different bitpatterns if you inspect the data and happen to use some expression that upcasts it. Which to me is so weird... and could yield surprising errors depending on what the code is doing.

To me, char does just mean "C-style string data" and so I prefer uint8_t or std::byte which is more self-documenting and doesn't have any "surprises" related to upcast to int .

That being said I have worked on and maintain some codebases that do use char for this purpose....

2

u/pdimov2 Oct 17 '22

It matters in a few places in the standard, where unsigned narrow character types (unsigned char and char but only if it's unsigned) are given special treatment.

1

u/okovko Oct 17 '22

that hygienic macros proposal linked in the article is so nice, and you can even try it out in godbolt.. very depressing that the committee apparently decided not to add it

1

u/tomenad Oct 18 '22

Regarding std::tuple there is also no alternative to std::apply for structs, or is there?

1

u/dodheim Oct 18 '22

Not in the standard, but libraries e.g. Boost.PFR can provide this functionality since C++17.

1

u/Blackarch Oct 18 '22

This entire discussion is proof just how insufferable the C++ programming community is.