Why STL implementation is so unreadable? How C++ could have been improved here?

前端 未结 3 1406
一整个雨季
一整个雨季 2021-01-01 09:01

For instance why does most members in STL implementation have _M_ or _ or __ prefix? Why there is so much boilerplate code ?

W

相关标签:
3条回答
  • 2021-01-01 09:30

    In addition to the good reasons robson and AshleysBrain have already given, one reason that C++ standard library implementations have such terse names and compact code is that virtually every C++ program (compilation unit, really) includes a large number of the standard library headers, and they are thus repeatedly recompiled (remember that they're largely inlined and template-based, whereas the C standard library headers only contain a handful of function declarations). A standard library written to "industry standard" style guidelines would take longer to compile and thus lead to the perception that a particular compiler was "slow". By minimizing whitespace and using short identifier names, the lexer and parser have less work to do, and the whole compilation process completes a little bit faster.

    Another reason worth mentioning is that many standard library implementations (e.g. Dinkumware, Rogue Wave (old), etc.) can be used with several different compilers with widely different standards compliance and quirks. There's frequently a lot of macro hackery aimed at satisfying each supported platform.

    0 讨论(0)
  • 2021-01-01 09:34

    Lots of STL implementations also include checking for debug builds, such as verifying that two iterators are from the same container when comparing them, and watching for iterators going out of bounds. This involves fairly complex code to track the container and validity of every iterator created, but is invaluable for finding bugs. This code is also all interwoven with the standard release code with #ifdefs - even in the STL algorithms. So it's never going to be as clear as their most basic operation. Sites like this one show the most basic functionality of STL algorithms, stating their functionality is "equivalent to" the code they show. You won't see that in your header files though.

    0 讨论(0)
  • 2021-01-01 09:49

    Implementations use names starting with an underscore followed by an uppercase letter or two underscores to avoid conflicts with user-defined macros. Such names are reserved in C++. For example, one could define a macro called Type and then #include <vector>. If vector implementations used Type as a template parameter name, it would break. However, one is not allowed to define macros called _Type (or __type, type__ etc.). Therefore, vector can safely use such names.

    0 讨论(0)
提交回复
热议问题