What does STL lack?

Source: Internet
Author: User
Tags traits

It is estimated that this article will be written again by some "Bricks", but today I suddenly want to reflect on the STL source code analyzed during this period of time, so I have this article. this is my personal opinion, and we hope that the "brick-and-mortar" people will show their mercy.

What is STL (here )?

STL = standard template library, a standard template library, is an important part of modern c ++ program design and a part of the C ++ standard, generic programming (generic programming) corresponding to the programming paradigm ). Its core idea is the separation of data and algorithms, which leads to the emergence of algorithm (algorithm) and container (container ), the tool that connects the two is the iterator that acts as the binder ), this demonstrates a famous saying in the computer world that "any problem can be solved by adding an indirect layer ":-).

The creation of STL is highly reusable and highly configurable and scalable. We can optimize it as needed. In the C ++ standard, STL is organized into the following 13 header files: <algorithm>, <deque>, <functional>, <iterator>, <vector>, <list>, <map>, <memory>, <numeric>, <queue>, <set>, <stack>, and <utility>. For historical reasons, the very important data structure hash_table is not added, which cannot be said to be a pity, but the boost library solves this problem (BTW, every feature in the boost library can be seen as a compensation for C ++ language defects: P). In fact, in common STL implementations, such as the sgi I am profiling
STL (here) provides the implementation of

STL advantages

Now that we want to talk about what STL lacks, Let's first look at what STL can do and what advantages it has.

First, STL encapsulates common data structures to avoid programmers repeatedly inventing the wheel of the same function (in fact, many languages directly provide support for basic data structures, such as Java ).

Secondly, STL is a series of highly configurable, reusable, and scalable components, and its algorithm efficiency is very high, to a large extent, it is equivalent to or even more than the code written by a majority of programmers (let's look at sgi stl's <stl_alloc.h>, and its memory pool design is extremely clever and can be called a work of art ).

Again, STL provides excellent portability capabilities that can be used on different platforms.

Finally, STL can greatly improve the programming efficiency of programmers.

The following is a simple example to show you how powerful STL is:

# Include <iostream> # include <string> # include <algorithm> # include <vector> # include <iterator> using namespace STD; int main () {vector <int> VEC; int input = 0; // use CIN and EOF to end, press the key to raise the platform // windows --> Ctrl + z // Linux --> Ctrl + d While (CIN> input) {// The container size can be dynamically adjusted here, it reflects the flexible VEC of STL. push_back (input);} // by default, STL uses the ascending sort (VEC. begin (), VEC. end (); // output all elements and separate them with spaces (VEC. begin (), VEC. end (), ostream_iterator <int> (cout, ""); Return 0 ;}

Think about it. How long will it take for you to write this program completely? How long does debugging take? It took me five minutes to complete the STL version of the program. Is it very powerful?

Insufficient STL

Since we have written a specific example, let's talk about the shortcomings of the above example:

# Include <iostream> # include <string> # include <algorithm> # include <vector> # include <iterator> using namespace STD; int main () {// The default vector constructor is used here. Depending on the implementation, the memory space may be reserved, // or not reserved, for example, the sgi stl I analyzed won't reserve the memory vector <int> VEC; int input = 0; while (CIN> input) {// if the data volume is large, frequent memory allocation may occur, resulting in high overhead. // the solution is to call reserve () for memory reservation, but this requires a lot of programmers, we need to be familiar with STL to avoid some obscure problems. Vec. push_back (input);} // by default, STL uses the ascending sort (VEC. begin (), VEC. end (); // If wcout is used here, incompatibility may occur. For the solution, see the subsequent article copy (VEC. begin (), VEC. end (), ostream_iterator <int> (wcout, l ""); Return 0 ;}

Let's take a look at the above program error in the fedora 15 + codeblocks + G ++ environment:

/Home/MDL/sourcecode/boosttest/main. CPP | 29 | error: For 'std: ostream_iterator <int >:: ostream_iterator (STD: wostream &, const wchar_t [2]) 'The call does not have a matching function |/home/MDL/sourcecode/boosttest/main. CPP | 29 | Note: Alternative: |/usr/lib/GCC/i686-redhat-linux/4.6.0 /.. /.. /.. /.. /include/C ++/4.6.0/bits/stream_iterator.h | 187 | Note: STD: ostream_iterator <_ TP, _ chart, _ traits>: ostream_iterator (const STD :: ostream_iterator <_ TP, _ chart, _ traits> &) [with _ TP = int, _ chart = char, _ traits = STD: char_traits <char>, STD :: ostream_iterator <_ TP, _ chart, _ traits> = STD: ostream_iterator <int>] |/usr/lib/GCC/i686-redhat-linux/4.6.0 /.. /.. /.. /.. /include/C ++/4.6.0/bits/stream_iterator.h | 187 | Note: Option 1 requires real parameters, but provides 2 |/usr/lib/GCC/i686-redhat-linux/4.6.0 /.. /.. /.. /.. /include/C ++/4.6.0/bits/stream_iterator.h | 183 | Note: STD: ostream_iterator <_ TP, _ chart, _ traits>: ostream_iterator (STD :: ostream_iterator <_ TP, _ chart, _ traits>: ostream_type &, const _ chart *) [with _ TP = int, _ chart = char, _ traits = STD :: char_traits <char>, STD: ostream_iterator <_ TP, _ chart, _ traits >:: ostream_type = STD :: basic_ostream <char>] |/usr/lib/GCC/i686-redhat-linux/4.6.0 /.. /.. /.. /.. /include/C ++/4.6.0/bits/stream_iterator.h | 183 | Note: no known conversion for argument 1 from 'std: wostream' to 'std: ostream_iterator <int>:: ostream_type & '|/usr/lib/GCC/i686-redhat-linux/4.6.0 /.. /.. /.. /.. /include/C ++/4.6.0/bits/stream_iterator.h | 171 | Note: STD: ostream_iterator <_ TP, _ chart, _ traits>: ostream_iterator (STD :: ostream_iterator <_ TP, _ chart, _ traits>: ostream_type &) [with _ TP = int, _ chart = char, _ traits = STD: char_traits <char>, STD: ostream_iterator <_ TP, _ chart, _ traits >:: ostream_type = STD: basic_ostream <char>] |/usr/lib/GCC/i686-redhat-linux/4.6.0 /.. /.. /.. /.. /include/C ++/4.6.0/bits/stream_iterator.h | 171 | note: the alternative requires 1 Real parameter, but provides 2 |||=== build finished: 8 errors, 0 warnings = |

I don't know what you think in the face of such a bunch of prompts. This is the first drawback exposed by STL. Once an error occurs, the prompt information will be very obscure.

Of course, this is only a deficiency that STL can see on the surface. What are the shortcomings in the deeper level?

First of all, STL did not take thread security into account during design. They thought this was the programmer's responsibility. Okay... I admit it, but how many people can solve this problem? Why is it not supported at the language level? But the good news is that C ++ 0 can support thread synchronization at the language level. Similarly, in the sgi stl <stl_alloc.h> I analyzed, its support for thread security is only at the Allocator level, and algorithms and containers cannot enjoy such benefits.

Secondly, STL teaching has never been given due attention. How many universities teach STL when they teach C ++?

Thirdly, if you do not know enough about STL, it may bring very low efficiency. See the following code:

# Include <iostream> # include <string> # include <algorithm> # include <vector> # include <iterator> using namespace STD; Class expensivecopyobject {public: expensivecopyobject (string hugedata = string ("this is a very long string .......................... ..... "): hugedata _ (hugedata) {cout <" construct "<Endl ;}~ Expensivecopyobject () {cout <"destruct" <Endl;} expensivecopyobject (const expensivecopyobject & other): hugedata _ (Other. hugedata _) {cout <"copy" <Endl;} expensivecopyobject & operator = (expensivecopyobject & RHs) {cout <"ioperator = ()" <Endl; this-> hugedata _ = RHS. hugedata _; return * This ;}//...... PRIVATE: String hugedata _;}; using namespace STD; int main () {// think about the overhead of this vector if the memory is not used again How big is it? // A better method is to store pointers in a vector, but this requires the programmer to control the pointer lifecycle. // This can easily cause a wild pointer problem, so it is not recommended // the best solution is to use: boost: shared_ptr // For details, see the subsequent article vector <expensivecopyobject> VEC (10 ); //........ return 0 ;}

Finally, the learning curve of STL is steep, and its design concept also takes a long time to reflect on it in practice to comprehend. Originally, C ++ syntax has been a headache for many people, not to mention the virtual function tables and other things. As for the repeated attacks during template debugging, many people chose to leave and switched to simpler languages such as Java and C. Even if I stick to it, how many people are willing to spend time exploring the treasures in STL source code? This has become a hindrance to STL development.

Suggestions and ideas

First of all, I don't want C ++ to provide us with socket, database encapsulated class libraries. I just want C ++ to provide us with a stable library and common functions, libraries like boost should really be added to the standard, which can greatly reduce the burden on programmers. You may say that using a third-party library can also achieve the goal, but if the C ++ standard sets out, then we can have a stable interface without worrying about libraries with similar functions.

Secondly, since C ++ 0x supports thread synchronization at the language level, there is no reason why the STL and boost libraries do not provide thread security ?! This is what I look forward!

Again, it is a highly controversial mechanism for garbage collection. I think it is really necessary to add this mechanism. In Windows, if you use a self-painted interface, even if you use shared_ptr and scoped_ptr with weak_ptr, it may cause memory leakage, so I hope to add a feature of selective hosting.

In most STL implementations, the support for assert is insufficient. In many cases, you do not know where the problem occurs. If you have more assert for verification, debugging will be very convenient.

In the end, this may not be seen in my lifetime, that is, to change the names of historically problematic functions in C ++ to something that is easier to understand...

Conclusion

The above points are purely my personal understanding. Please show your mercy on the "brick house" and "called the Beast". If I really have any misunderstanding, please criticize and advise.

Errata

Concerning STL thread security, I have discussed it most. I have tested it and confirmed the non-Necessity and difficulty of providing thread security.

If we want to provide thread security, first consider the container security, and we lock the write and read operations of the container, this can meet the security of my single access, however, you still need to lock the security of the business logic, so the lock at this layer is redundant and useless, and will bring unnecessary burden. The following code describes the situation:

# Include <iostream> # include <string> # include <algorithm> # include <vector> using namespace STD; const int veccapacity = 100; int main () {typedef vector <int> intvec; intvec (veccapacity); // assume that the VEC [] operation is thread-safe, can we ensure thread security when the program process is in [2? // The answer is no, because a value assignment operation is followed, the program may switch the thread here. // if another thread performs some operations on VEC, the result is certainly not what we expected. Similarly, when the program is switched in [1], assuming that another thread modifies VEC [I-1], // The result is not our expected behavior. // This is just a vector <int>, which brings so many problems, if it is not an int, but some objects that need to be processed before they can be used, the consequences will not be considered for (INT I = 0; I <veccapacity; ++ I) // [1] VEC [I] = I; // [2] // except for the above mentioned, pay attention to several details. // If the thread is switched in [3] or [4], if other threads operate on VEC, causing the iterator to fail, // then we may get the wrong result, not only the container content error, but also the business logic error for (in Tvec: const_iterator iter = Vec. Begin (); // [3] Vec. End ()! = ITER; ++ ITER) cout <* ITER <Endl; // [4] Return 0 ;}

As for the algorithm lock, similar to the above situation, it can only ensure the correctness of a single time, but cannot guarantee the overall correctness.
Another idea is to lock the iterator. This solution can only solve a small part of the problem. If it involves passing the iterator into other functions, the complexity of the problem increases exponentially, therefore, this solution is unrealistic.

Therefore, providing thread security for STL not only increases the complexity of STL implementation, but also creates a high burden. However, the thread security we expect has not been implemented yet, therefore, STL does not provide thread security, which is the correct choice.

I am sorry for the previous incorrect assumptions. I would like to thank all the brothers who have pointed out the mistakes to me.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.