r/cpp • • Jun 10 '20

Why is std implementation so damn ugly?

Recently I remembered a moment from my uni years when immediately after handing in the assignment of implementing our own string data structure we were warned not to ever try to implement and use our own data structures. Which is exactly what you want to hear after working hours on such assignment. However the reason behind it makes sense, you would be only reinventing the wheel and let's be honest, it will be also way slower than data structures in the almighty std library. Now think about it, what kind of black magic is behind the std's speed? Well I had no idea so I took a peak, lets see the code:

inline string
secret_function(int __val)
{
    const bool __neg = __val < 0;
    const unsigned __uval = __neg ? (unsigned)~__val + 1u : __val;
    const auto __len = __detail::__to_chars_len(__uval);
    string __str(__neg + __len, '-');
    __detail::__to_chars_10_impl(&__str[__neg], __len, __uval);
    return __str;
}

Hey, I bet you just skipped the whole code part. I know it looks unreadable, but please try to go through it and guess which std function it might be (obviously its not called secret_function, but i'm pretty sure you used this function at some point).

It's only 6 line function but it took me a while to figure out what each line does and I believe this could be fixed very easily just by naming the variables and functions with a bit more descriptive names. Just to prove the point here is an example of how I would structure this function:

inline string secretFunction(int value) {
    const bool isNegative = value < 0;
    const unsigned absoluteValue = Helper::abs(value);
    const auto length = Helper::charCount(absoluteValue);
    string stringValue(isNegative + length, '-');
    Helper::insertIntAsChars(&stringValue[isNegative], length, absoluteValue, 10);
    return stringValue;
}

While the functionality stays exactly the same, I think this chunk of code is much more pleasant to read and it's pretty obvious what the code is doing on each line. From this you should have a solid guess which function it is (you can leave a comment), but the real question is why would anyone write such code? Especially when nowadays everyone is talking about how code readability is so important. Is this how they wrote code back when std was released and they didn't bother to change it? Or am I just too inexperienced that I couldn't figure it out immediately?

EDIT: Thanks for the insightful comments, for anyone reading this the reason variables are beginning with __ is macros. If user defines isNegative macro, it will get overwritten in the std, however user is forbidden to define macros starting with __ , as the wise people of reddit comment section suggested. However underscores aren't the only issue with this code, the main issue is I think using short non-descriptive names of variables/functions which is very confusing in functions that are doing more complicated operations.

237 Upvotes

212 comments sorted by

View all comments

170

u/thedictatorofmrun Jun 10 '20

There is a lot to unpack here, so this might be a bit long.

Another comment has already touched on the reasoning behind the leading underscores being to avoid collisions with macros.

You seem to make the assumption that the standard library is extremely fast, moreso than anything a mere mortal could write. This is wrong. The standard library does have pretty good performance but for specialized applications it is definitely possible to beat it, and for simple things like vector/array/string it is not difficult to match it. The strength of the standard library is that it is performant enough for the vast majority of applications, that it is designed to be very generic, and that it is, well, standard.

Additionally, readability is extremely important for most applications and libraries but the standard library isn't really one of them. You're not really meant to read or edit the standard library unless you are an expert, so readability is kind of a secondary concern.

Your translation of this function to be more "readable", incidentally, is actually probably less performant than the standard library version because (1) you are calling a separate function for abs rather than doing the twos complement inline and (2) you added a "base" argument to the "to chars" helper method which in the original version is known at compile time. Maybe you get lucky and it compiles down to the same thing, but in my opinion it looks like it'll probably be somewhat slower.

I will say that you probably are a little inexperienced with the style of programming that the STL uses, and with more experience looking at these definitions it will probably not be too hard to see what is happening in these functions. The only tricky thing I see here is the twos complement absolute value thing, and the rest of the confusion is probably just the naming conventions being unfamiliar.

181

u/MachineGunPablo Jun 10 '20 edited Jun 10 '20

While you provide really great criticism to OP's "improvements", saying that code readibility in the STL is a secondary concern is extremely debatable.

Some STL code is borderline impossible to read. In fact, there are parts of it that don't even seem to be written by a human. And what is the consequence? That the STL is complete uncharted territory to the normal developer. The STL should be a showcase of not just efficient language usage but also of proper software engineering and coding practices. People should be able to find inspiration on the STL instead of running from it. People should be able to debug a crash inside the STL and make sense of variable names and program workflow. Readability is fundamental in software, specially for core libraries.

14

u/thedictatorofmrun Jun 10 '20

I'll admit that I don't dive into the STL implementation often. I wonder how much of the illegibility of some parts of the STL is avoidable and how much is just always gonna be there is a performant, generic library providing what the STL does (like, there's probably never gonna be an implementation of a red-black tree that's super easy for a layman to read, right?)

7

u/ArashPartow Jun 11 '20

It would be interesting to see an example of illegible STL code that was there purely for performance reasons.

37

u/STL MSVC STL Dev Jun 11 '20

std::find's memchr optimization is incomprehensible to most programmers.

My hex precision rounding would be utterly incomprehensible without the comments.

1

u/thedictatorofmrun Jun 11 '20

is this memchr optimization just using memchr in find when you're searching for any kind of char, and doing a for loop otherwise? Admittedly its a little convoluted but most of that seems to be the hoops you have to jump through to decide which version to use at compile time (which in c++>=17 you could do much more easily with constexpr if or other things like that). Unless I'm missing something?

4

u/STL MSVC STL Dev Jun 11 '20

It's a little trickier than that (and yes, we will simplify this dramatically with if constexpr soon). If you call find(char_ptr, char_ptr, 47) then your desired value is an int. We detect whether the int is within range of a char and if so, we call memchr. If the int is outside the range (e.g. 1729) then we return false because it can't possibly be within the range as viewed by find's theoretical use of ==. Unconditionally converting 1729 to char and calling memchr would be incorrect. (Activating this optimization only for matching value types would be easier, but more limited.)

1

u/thedictatorofmrun Jun 11 '20

Ah yeah I missed that originally. Thanks for explaining, that is a cool example. Glad to get some insider info in this thread