Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

What features C++ is lacking that would allow make vector (for instance) implementation clear and more concise?

like image 674
Łukasz Lew Avatar asked Sep 22 '09 15:09

Łukasz Lew


People also ask

How is STL implemented?

The STL is a highly optimized library that does most of what it does by cleverly exploiting advanced features of C++ and the underlying compiler. Additionally, many things are inlined so there is no real bunch of code to look at like in an application.

Can we use STL in C?

C can't have an "exact equivalent" of STL because C doesn't have templates or classes.

Is STL built in C++?

The Standard Template Library (STL) is a set of C++ template classes to provide common programming data structures and functions such as lists, stacks, arrays, etc. It is a library of container classes, algorithms, and iterators. It is a generalized library and so, its components are parameterized.

Is C++ STL fast?

I spend a lot of time with the C++ Standard Template Library. It is available on diverse platforms, it is fast and it is (relatively) easy to learn.


2 Answers

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.

like image 152
robson3.14 Avatar answered Sep 20 '22 14:09

robson3.14


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.

like image 45
AshleysBrain Avatar answered Sep 22 '22 14:09

AshleysBrain