Downsides to the C++ STL?
craybob queries: "I'm a developer for a small software group that will soon migrate from using Rouge Wave to using the C++ STL. I just left the week-long Software Developers 2002 conference, where I heard the great minds in software tell us all of the best ways to take full advantage of the STL. (I just wanted to give a quick thanks to Stephen Dewhurst and Scott Meyers) From this I came away with the feeling that this is the Holy Grail of C++. I'm sure these guys are right and that it is great, but the truth is that I'm a skeptic, so what are the downsides to the STL?"
It's written in C++? :)
And have you seen the actual code for the STL? Ugh. It demonstrates just how bad and obscure C++ syntax can be.
-
I think STL is great.
About the only downside I've seen are old compilers bloating up the executable sizes if you use it a lot. I believe that's largely becoming an issue of the past, though.
"Provided by the management for your protection."
Depending on your compilier, you might end up with excessive binary-code bloat, as three different copies of "list" are created for list<foo*> , list<bar*>, and list<fred*> instead of using a single specilization for all three.
I don't know how well the inheritance issues are nailed down, but I've never been tempted to make a class inherit from a container, I just have classes have containers.
That said, I like STL and highly suggest using it. Never write a linked-list again.
Otherwise, the STL is an excellent set of libraries to move the OO paradigm towards parameterized types.
Of course like the rest of C++, you pay a price in comprehension...this language exposes everthing to you and you will pay a price in development and comprehension time.
Um...you don't know what you're talking about. The STL does not make use of virtual functions.
The fact that no compilers support all of STL is admitted by Stroustrop (sp?). However, in practice, most of it indeed works as advertised. You shouldn't have much problem.
But the real bear is the compilation error messages, which can be pages long, and ultimately completely unreadable. This is due to template expansion, especially with STL classes (most of them) that take a large number of arguments, most of which have default values already.
Also, as with all templates in C++, there is code bloat. But it is a tradeoff between having more code or having better type checking. You have to decide what is right for you.
In terms of usability, the STL is great. I've been told that it's not the be-all and end-all as far as performance goes, but it can handle most applications, even situations where there IS a performance requirement as long as it's not an especially stringent one.
We developed a call-routing application for Solaris in C++ using ACE and the STL, and were able to meet a fairly hefty performance goal.
The biggest downsides on the STL that we encountered were a few compile issues in terms of integrating ACE into the build (not a big deal), and the larger one of somewhat poor documentation of the STL itself. We used the MSDN STL documentation, and while Microsoft's implementation may agree with that API spec, Solaris' certainly didn't. See the signature of the map::delete method for an interesting example.
Both the Solaris (actually SGI) and RogueWave implemementations DO NOT match the documented interface, even though Rogue Wave's documentation says it does! So make sure your intended usage is actually supported by the implementation of the STL that you're using.
Xentax
You shouldn't verb words.
The thing that always bites me in the ass is the string class.
string foo = NULL;
This always gets me, segfault.
I do a..
string foo = "";
where I define ""; as NULLSTR in some header.
I dont know if this is a real problem or no its just that i have the habbit of initializing stuff to NULL.
My bad style.
If I were only smart enough to accomplish the things I dream about.. Or maybe too dumb to care.
The big downside is executable code bloat if your compiler isn't good at optimizing away unneeded generated template code. The STL is almost entirely template-based. You could also call it a downside that you need a fairly current compiler because the STL makes heavy use of recently-introduced template features that even moderately old compiler versions won't understand.
You also get a certain amount of lock-in, where stuff that deals with STL-using modules also tends to need to use STL to pass the right containers around, but you can deal with that in wrapper layers and IMHO the gains make the little extra work worth it.
What are you talking about? The STL uses templates for genericity, not virtual functions. And no, there isn't a lot of overhead when you use the STL if you watch the things you're doing. Any overhead incurred by virtual functions (and it's typically dwarfed by whatever you do inside the functions called) is predictable, and shouldn't cause "havok" on your real-time requirements. Admit it, you're talking out of your ass.
But templates increase code size as the compiler has to genarate a different version of the class for each unique instance that you use.
ie. If you use a Vector to hold 15 different things, the compiler has to generate 15 different version of the Vector class to compile your project.
May not be that much of a problem if you've got the memory.
Too bad I don't currently have any moderator points, but I agree with this statement.
It really helps to pre-plan what you're going to do with the STL (I guess that goes with everything else in software dev). It can get really ugly if you use them on-the-spot as you hack away at an implementation. But if you think it through, you can control the costs of using the STL. Pre-plan and take advantage of C++'s "pay only if you use it" philosophy.
(\(\
(^.^)
(")")
*beware the cute-bunny virus
The C++ language spec explicitly specifies the performance requirements for STL components (which is rare in a language spec, IMO)... the brunt of the work is at compile time, and there is no virtual function dispatching in the STL.
As with OOP itself, generic programming is a Really Good Idea but its implementation in C++ leave something to be desired for simplicity and accessability. Due to C++'s dominance in the marketplace, the STL will likely be with us for many years, but this is far from a desirable circumstance.
Just to add to the parent... That's right. STL does not use virtual functions. In fact, STL is not an object oriented library at all. It's generic programming, and it's the coolest thing that I have seen for C++ ever. (Now is the place where LISP programmers can shout out that they've been generic for 40 years.)
If tits were wings it'd be flying around.
If your building an application, then you will not want to use STL. STL is a speed deamon. It will be great for coders that write to hardware (ex: phone switches, automotive computers, etc...). Templates is the name of the game here, and because of the lack of objects, the programmer enjoys the power of C++, and the speed of the older style ANSI C compilers.
STL doesn't normally use virtual functions, unless some of the comparison functions or functor objects do. The main cause of bloat (in my experience) is the lack of provided specializations, and the huge symbol names generated by name mangling.
(Fer fun, create a map< foo, map<bar, map<fred, qux> > >, and run "nm" on the generated .o file. I had a problem with blowing up the size limits on the default Solaris linker with stunts like that)
The benefits of using STL are wonderful. If you write your custom containers/streams/etc. using the STL interface, you can seamlessly use the algorithms portion of the library.
I recommend reading the first part of Generic Programming and the STL. It'll help you undestand the thinking behind the design.
I'll admit that I may have spoken rashly about the virtual functions, but my other points about templates and code bloat still hold true.
And it will cause havok if you're not aware of it.
Here it is, an ASCII rimshot:
\/!
This is my invention, which is mine.
Overall, I consider the STL well worth your while to learn and use.
"Before enlightenment: sharpen claws, catch mice. After enlightenment: sharpen claws, catch mice."
The last book in Myers effective triology goes into a great number of details about the pitfalls of STL
One thing to be wary of (as many have pointed out) is the different implementations of STL. GCC pre-3.x is pretty non-standard (although not necessarily bad). MSVC pre-6.x is absolutely horrendous (from what I gather, this is more of a legal issue than MS's fault).
Some of the wackiest things though IMHO are:
- Never use vector! It's a horrible specialization and is not even a container. Very, very bad.
- Allocators are for the most part evil. Be very wary of them.
BTW: There is a book Efficient C++ that says a lot of bad things about STL. This book absolutely sucks and is full of nothing but crap. While the examples aren't forged, they are examples of how not to use STL. Unfortunately, the book presents non-STL solutions that aren't even as fast as the proper STL solution. Long and the short of it is, make sure you (and your developers) are very familiar with STL and be aware of bad information about it.
int func(int a);
func((b += 3, b));
For it being the 'holy grail' in software development, it seems like the poster could have dug up some sort of linkage for those not hip with exactly what STL truly is all about...
For the ill-informed, please see the following links concern the C++ Standard Template Library (STL):
*** Mumit's STL Newbie guide
*** Standard Template Library Online Reference Home Page
*** Another Informational Link
There, I feel much better.... and hopefully you do, as well!!!
Beer is proof that God loves us and wants us to be happy. -- Benjamin Franklin
Before you listen to any of us, go out and buy "Effective STL" by Scott Meyers, and probably "The C++ Standard Template Library" by Nicolai M. Josuttis.
Now, I don't want to get off on a rant here, but in my personal opinion, the worst thing about STL is their string support. It's great, because it's standardized, but that's about the only thing going for it, from a programmer's perspective. (Yes, it's highly optimized, but the API isn't very rich. I like rich APIs!) In other words, build your own string class, and give it a Has-A relationship to the STL string.
Also, I hate that Containers change paradigms on you, some places you can use integer indecies, sometimes you have to use iterators - and in my opinion, the line isn't very clearly drawn.
Also, the methods are written along the lines of, "if it's not optimal, you have to write the code yourself." I'm sorry - that sucks. Sometimes I need to remove an element from a Vector. Maybe I should be using another Container. Or maybe the API should allow it, but make it clear in the documentation that it's not efficient. I vote for the latter.
Get used to having your objects copied. STL Containers work by copying your objects. It's a different way of thinking for a lot of people. It has rammifications that are kind of hard to grasp, at first, if you're not used to it.
Don't use Containers of AutoPtr's! It won't work right! (Read "Effective STL" for an explanation.)
In my opinion, everyone should wrap every third-party library they use with an API that they can live with. STL is no exception. You might even expose every single member function, but you have the freedom to expand your API if you want. If you can't afford a stack push, then you probably shouldn't be using STL in the first place.
If you end up really liking STL, take a look at Boost. Some parts of Boost are really cool and well written.
Really, I think the best advice I can give is this : get to really know an API before you start to use it. Because, if you try to just use the parts of an API that you know and like, you're going to make horrible mistakes. Invest the time to get to know the library well enough to use it the right way. STL is no exception.
Of course, that's just my opinion, I could be wrong.
Education is the silver bullet.
Easy way to solve this problem known as the "swap trick." This will work with any container (and strings) and is the only way to guarentee a reduction in capacity.
//reserve bunch of memory
//even though size is 0
//swap the elements from an
//empty temporary including
//swapping capacity
vector v(10000);
vector().swap(v);
int func(int a);
func((b += 3, b));
The main problem with the STL is that it relies heavily on inline functions, and many compilers (GCC included) still have very poor inline optimisation. The GCC variant we use for the PS2 (ee-gcc) has a terrible habit of inserting spurious writes back to memory, causing all sorts of unnecessary stalls.
Perversely enough, despite the unreadable and buggy implementation shipped with it, Visual C actually produced remarkably good object code from it. The vector class in particular was more efficient than many of the hand-rolled examples I've witnessed during my career.
...
Virtual functions, as others have noticed, are a complete red herring, as the STL doesn't use them, and any moderator with an ounce of sense would mod parent down for being uniformed karma whoring bollocks.
I am an avid user of STL, and I have worked on many projects, large and small, that make use of it.
Advantages of STL:
- Standardized, comes with every C++ compiler
- Fast
- Generalized (excellent use of templates)
- Many different implementations freely and commercially available.
- Source code available.
Disadvantages of STL:
- Large executable file sizes
- Incompatibilities between implementations
- Complex to debug
STL is a very fast and powerful library. Ignore those who say "it uses virtuals, and is in C++, therfore it is slow" because none of them have ever used it. (C++ is in fact faster than C if coded properly, and STL is coded properly) Often, a good structure is much faster than using arrays, even if they have less overhead.
Unfortunately, STL's use of templates and inlines can inflate the size of your code in exchange for raw speed. This can vary very much depending on your compiler. MSVC adds 200k or more just for the priveledge of using strings! Using STLport still requires that you link in the old 200k libraries ON TOP of STLPort!
I do not recommend using STL on small projects where compiled file size is an issue. For anything else, go for it.
The tradeoff on binary size for code readability and maintainability (and execution time, of course) can be well worth it, IF you have the memory to spare. Our target machines rarely have less than 1GB of RAM, so it's not been an issue.
You shouldn't verb words.
STL = Standard Template Library
It basically defines a lot of common tools that you can use with your program specific needs such as lists and queues.
Nosce te Ipsum
First of all, STL is not some proprietary set of binaries given to you to run to make your life easier in a black-box scenario. You're given the complete source for every bit of it. Yet for this reason, at some point in your development career, you'll feel like something in your code is written perfectly fine and that it "the STL" that has the bug. And then you step into the source while debugging. And then you curse everyone who ever had any part of coming up with this bunch of fscking nonsense. Then you completely give up, go grab a Dr Pepper, start over and skip over those STL calls instead of stepping into them and realize it was indeed your bug. I've heard various reasons in the past about why STL implementors release code that looks like an obfuscated-C contest winner (i've even heard that was the reason before), but I still don't buy any of it. There's no way they wrote it that way originally (so why did they change it), are they scared of whitespace (why?) and comments (did they ever read McConnell or Macguire?).
Second beef with STL is that although it *should* be standardized by all implementers, just like everything else that *says* it is, it is not. The STL implementation that comes with MSVC++ (a hacked up version of Dinkumware's I believe) has several subtle differences from all other implementations. And this is true for several compilers that come stock with STL. Don't immediately expect to port STL-based code from one compiler to another. Our company has to switch between two different implementations to compile between MSVC for a Win32-based build and MS Embedded C++ for a WinCE-based build. Sad but true. That's my beef.
SGI's reference is excellent. It covers the entire STL standard (the few SGI-specific extensions are clearly marked), and is very well written.
Unlike an inheritcance-based container,
like those in Java, the
template-based containers of STL
do not use virtual function calls to achieve
genericity. Although this may result in an
increase in code size, there are cases
where different types can use the same
code at runtime. For example, a container
of int * and a container of char * might use
the same object code.
Some of the benefits of template-based containers
over inheritance-based containers are:
1) static type checking
2) can hold non-class type objects.
3) no virtual function call overhead.
To elaborate on item 2: If you want a
container of intgers in a Java container
(i think) you have to have a container of
"Int" rather than "int".
Standard Template Library
We had a nasty bug like that too -- the strange thing was that gcc was ok with the symbol name lengths when we compiled for debug, but something in our release build flags (the optimization level I think) would truncate the symbol names, which then caused naming conflicts, etc...quite a mess.
Xentax
You shouldn't verb words.
Standard Tamplate Library. It is a standard C++ library that provides containers and generic algorithms. The power of the STL comes from abstracting the concept of a sequence - the algorithms work on linked lists, c arrays, vectors - anything that provides iterators. For example, the following function will return the sum of all the elements in a sequence (off the top of my head, did really compile this):
template
double sumOf(TIter start,TIter end){
double result=0.0;
for(TIter curElement=start;
curElement!=end;
++curElement){
result+=*curElement;
}
return result;
};
You mean it is a trade off between having a larger binary or having better type checking. Using the STL and templates, you will tend to have less code, not more. But binary bloat can be a real issue.
I am on a research team that is developing a Bluetooth financial transaction system. One of the members of our team wrote an XML parser using STL components. When it came time to compile the XML parser using the embedded tools for a PDA, we found that Microsoft had not implemented the STL in the libraries they provide in Windows CE. We had to switch all our string processing to use Windows components like CString (which, admittedly, has more features that the STL's string). The moral of the story? Using STL may affect your portability, especially in the embedded systems arena.
An unjust law is no law at all. - St. Augustine
STL, as all the previous posts have mentioned, does not involve virtual inheritance overhead (unless, of course, you derive from the STL - YOYO at that point).
however, that doesn't mean that there aren't any "cons" to the STL. if you don't catch exceptions thrown back from a contain, your bound (no pun intended) for trouble. expect performance hits if you insert into a vector, or you don't allocate sufficient memory ahead of time. the STL only wraps common data structure and their operations - the idea being that you don't have to write a list for Class A and Class B and Class C; you can just create a template of a list that holds a Class A or Class B or Class C. the behavior of a list is similar, the only difference between lists is what they hold.
perhaps what bill was really try to say was "there is a lot of overhead with using C++" for embedded and realtime platforms. that, i would agree with - to an extent. i would have to say that the big performance hit on a RTS w/ C++ would be vlookups against the vtable - but how would that compare to a large switch-case block? the vtable itself may consume a bit more memory, but it might cost much less in manhours and frustration to work with derived classes than to maintain switch case logic. remember, every time someone adds some new functionality, someone has to go through a full compilation/regression test w/ a switch-case. by adding a derived class, you only need to compile/test the class itself.
Me email iz skyewalkerluke at microsoft's free email service.
The biggest drawback of STL is finding something to do with all the extra time you'll have. Just think--you won't spend days debugging somebody's insanely API'ed String implementation he developed when wired to the gills on Jolt.
You won't spend discouraged hours in meetings while ego-driven idiots argue over whose pet collection class hierarchy better suits the hypothetical abstractions of the project. You won't waste precious energy trying to reverse-engineer someone else's pattern building-blocks because now you immediately recognize STL method signatures.
STL reduces job security for programmers who rely on obscure implementation. Some may see that as a drawback. IMHO, good code is maintainable code, and STL usage in any project is a quantum jump towards maintainability. Remember, the "maintainer" will probably be yourself revisiting the code six weeks after that all-nighter.
Remain calm! All is well!
The biggest downside of the STL is when it doesn't work.
/. more recently), and the executables are freaking huge.
Sure, the standard is >3 years old now, but a lot of compiler vendors are still working out bugs with either the STL, their compiler, or their linker still.
Under AIX, we've run into relatively few problems with the STL itself, but the linker is pretty bad. Between it and the compiler compiles take forever (which is why I've been surfing
This is, obviously, an AIX-specific problem. And it's pretty much an old story - every vendor has their own quirks with the compiler and/or linker.
Beyond that -- I've found a few things missing in the STL that would be really nice to have.
First, the only smart pointer is std::auto_ptr. It's pretty useless, since you can't use it in a collection, and you can't have more than one thing pointing at an object/memory block at once. This can be worked around though, since there are libraries that have better smart pointers. Check out Loki or Boost for two.
Second, there's no way to automagically ignore case on a std::string, or to upper/lower case it easily. Yes, I know, you can muck around with traits, but that's a PITA and renders your string uncopyable to other strings easily. Yes, I also know that you can use a transform() to do it. But this still isn't as nice as myString.lower().
Third, there's no date or datetime classes. You have to fall back on C time functions for them. I haven't looked for a good C++ library to handle date/time, but I'm sure there's one out there.
Fourth, there's no regular expression matching on strings. We use PCRE with a C++ wrapper and it works fine for what we need though.
Both 2 and 3 are due largely to internationalization issues... in the case of 2 there's a lot of languages in which upper and lower case are non-sensical. And after having thought about the i18n issues regarding dates, I don't blame the standardization committee a bit for running away screaming from them (what date range? which calendar? how do you change between calendars? what about date weirdness with some calendars (like the missing days in the Gregorian calendar)? etc).
I used RogueWave prior to this job, so I tried to think of some of the things I was used to in RW and weren't in the STL. By and large I prefer the STL though. The container classes in particular are a lot more sane than RW's.
Cycle repeats.
Eventually though, when you reach the top level and discover a bug 5 levels down and try to decipher the compiler error, and then hunt it down... well that's when I start to hate C++.
-
If C++ had had its act together in 1992 and had a decent set of libraries agreed upon etc etc things might have been different. At this point however the announcement appears to be about as significant as when Fortran 8X was finally accepted and became Fortran 90, would have been nice to have happened five years earlier.
At this point the momentum in the software industry lies firmly with Java and C#. I know plenty of programmers who thought that C++ was worse than C. Java would have been the answer if Sun had not insisted on maintaining absolute control over it. [I don't care how open they claim to be, open means that other companires can make changes that Sun might not like, no language can be kept 100% pure and be open to unrestricted modification]
Todays announcement is not likely to have much relevance for existing projects. Once you have started to code to one library you is kinda stuck. I don't think many people will be kicking off completely green field C++ projects in the near future.
Looking for an Information Security student project suggestion?
Try http://dotcrimeManifesto.com/
First off: Why must you use STL? STL can be handy, but it can also be a terrible pitfall to the unwary. If your code is working and there is no compelling reason to re-write it, then don't/
Secondly: Be very, very careful about using pointers to dynamically allocated objects. If you are copying pointers around, you could very easily get into a dangling reference. A smart-pointer template (which SHOULD have been part of the STL) is a handy thing to have.
Third: Take the time to learn the Zen of STL. You must understand the rationale and mental model of the STL to get the most out of it. It doesn't take long (a week at worst).
Fourth: Get a good C++ and STL implementation. If you don't, you could wind up with compile errors that will drive you insane. <Sounds like the voice of experience, MagikSlinger!>
Fifth: Use STL sparingly. Don't go hogwild creating types made up of a dozen composited templates. When you get a run-time error or compile error, it becomes next to impossible to decipher what happened. Do not go more than two levels deep in an STL definition. map<string,MyClass> is OK, map<string,map<pair<T,X>,list< vector<int>>> is a very, very bad idea...
Sixth: Use the simplest datatype to achieve your goal. Don't resort to multimap, etc. with fancy indexing/hashing schemes unless you prove emperically that it will speed something up a lot. Not a little bit, but a lot.
Good luck, and have fun!
The bitter lessons of a veteran coder: http://bitterprogrammer.blogspot.com
I hope you're not talking about re-writing existing code to use STL instead of the equivilent C++ libraries. That sounds like a great way to introduce insideous bugs in your code. If it ain't broke, don't fix it.
In our development team, we have people who prefer RW, others who prefer the STL and others who are agnostic. In general, we've had a very good experience getting them to work together. Sure, it tends to lead to larger executables, but that's not a particularly big issue for us.
One thing that I haven't seen others talk about is that the two do not necessarily perform equivilent functions. The STL provides a bunch of templates, and RogueWave provides a bunch of useful classes, some of which are templates. RWTime, for example, has no equivilent in the STL.
Also, if you want to use other RW libraries (such as their threading stuff), then you're going to need to use some of the base RW stuff anyway.
Actually, STL is blistering fast and the size increase of marginal compared to a C equivelent. On some platforms (Linux being one), the STL code is in a shared library to reduce the executable size.
Instead, imagine what you are gaining. You get a good string class. No more worring about if the buffer is big enough or having to realloc/free memory when a string is appended or no longer required. It makes buffer overflows history.
Hash's and Trees: you can do this in C/Perl/Delphi/whatever, but STL's implementation is very easy to use and is optimized like crazy. The STL writers are very proud of their algorithms' performance. This may be one of the cases where it's impossible to write a faster C equivelent.
Portability. Anything written in ANSI C++ will compile anywhere as long as the compiler and libraries are up to date. A program I am working on will compile on C-Builder 4, Visual Studio, and GCC on Linux, without a single #ifdef or third party library.
The only downside I have experienced is that I needed to spend some money on books. STL has a learning curve and you might find yourself aging rapidly while fighting syntax errors that fill up the screen. But once you get the hang of it, STL is the easiest way.
Ozwald
Simply write a quick Perl script that "pretty-prints" the error messages. You want to remove the optional template arguments about custom memory management etc. Also, replace basic_sting with string. It'll work wonders.
Oh, and also, never look at more than the first error message. Fix it, and the rest will magically disappear :)
I manage a team that changed over our code base from RW to STL. The main driving force was that STL would be supported going forward were as we were using an unsupport version of RW on an unsupport platform.
The change over did induce some bugs as expected.
Code bloat, unreadable errors and other template issues are the same for STL as they are for RW so you shouldn't see any downside for items that are caused by templates.
In general RW had a fuller API set so you might find things that were easy in RW aren't quite so easy in STL. We generally wrote a wrapper function that added the RW functionality we lost then unit tested the wrapper fairly throughly.
One thing to watch out for in RW the sentinal position is at the begining of the collection and in STL it is at the end.
You do have to choose which STL to use. We are using the SGI version but will switch to the SCO/unixware native verion soon.
Get a good book I recommend "STL from the ground up" by schiltz.
The STL wasn't adopted because the committee liked it tremendously, it was adopted by default: it was the only serious proposal for collection classes for C++ that the committee had, and C++ needed collection classes in order to pass as a standard. I think what C++ should have gotten was a simple template array class, list class, and hash table class, with excellent error checking. IMO, STL has greatly damaged the C++ language.
How can you live with the C++ STL? Your best bet is to pick a small, simple subset of concrete STL datatypes and operations (vector, stack, and map) and stick to those in your interfaces and most of your code. You can implement your own, safe and efficient versions of those for development and internal use and use the standard STL versions when you ship library code. Forget about iterators: they are a mess to debug. And use the STL algorithms only if you don't care about performance.
Note that I have nothing against generic programming: generic programming is an old and well-established idea (and predates Stepanov and Lee by many years). C++ is just not a good language to push it to the extremes that STL pushes it.
You've read Meyer's book, which is a good start. You probably also want to check out Josuttis.
The STL is really as good as could be expected. Better even. There are problems. Some problems stem from the fact that it had to be approved by the standards committee. There was a lot of opposition to adding something that big to C++, so the size was cut down. Certain things are missing. (Heaps, general binders, good smart pointers) but versions are provided by many implementations. Check out CGI for one. They will also be added to the next version of the standard, along with a few other nifty things (As always check out boost.org for much of that stuff). The allocators are broken in my opinion. Using (different) customized allocators prevents interactions between your containers.
The biggest problem is its complexity. Like any C++ feature, understanding the STL is not enough. You need to understand how it interacts with other parts of C++. When you use the STL, you are using a rocket launcher instead of a BB-gun, shooting yourself in the foot can be much worse.
All in all the STL is god's gift to programmers. It really is. I can't imagine not having it to program anything serious with. I work everyday with AI and Image Processing algorithms -- stuff where performance really counts, mind you -- and I couldn't live without the STL. I barely use pointers anymore.
To sum it up, C++ with the STL is the only language that meshes (not always prettily) performance computing with high level concepts. It is a truly beautiful technology.
I use STL container templates extensively in my code and have sound them to, in general, be a major time saver. However, in the Microshaft world STL and DLL's don't mix well.
.obj) and (usualy) merged apon linking. This means that if you use the same template (e.g. std::map) in both the application and some DLL then you will have the same code in both binaries. For templates like vector and list this ok. But for templates like map this can cause problems. Templates like map and set have static member variables that they rely on (Microshaft implementation anyway). This means that if you create a map in the app and pass a reference to in into a DLL function that tries to manipulate the map the result is a memory access error. There are ways to avoid this problem but they limit your design options.
The main problem is that when useing templates the generated code is included in each translation unit (.o or
There are ways to get a template to be an "exported" class in a DLL but this only works with vector. The other container classes are structured such that this will not work.
Sigh, there are times when I really miss my last job (Solaris all the way) but then I remember what ^%#$%& my boss was.
You have to pay very close attention to where you are storing pointers or iterators, and to when the things they reference are freed or moved. It is very easy to misuse the automatic constructors and destructors in C++, especially if you don't understand exactly what the STL is doing "under the hood" for each operation you perform with it.
"Smart pointers" help, but they have their own bugs and quirks, too. (I once did "bidirectional" smart pointers that were pretty idiotproof; all ends of each multiway link were aware of each other, but this had a lot of overhead.)
You can minimize this risk to some extent by designing the code to pass around auto-constructed copies of data instead of references or pointers, but this will tend to impact performance, sometimes so much so that Java would be faster.
Multi-threaded apps are even harder to get correct, since STL is not generally threadsafe.
Oh yeah, looking at the mangled names when you debug your code will drive you insane.
Nevertheless, IMHO, the STL is still the best thing about C++ and is just about the only reason I would use it instead of C. (Either one, though, is a last resort. I tend to develop and test all code in something like Python, and port portions to other languages only as needed.)
I've gotten very frustrated with STL. Some problems are:
a) Microsoft has its own kludged-up-vaguely STL-like stuff (CStrings, etc.) and every Microsoft-brainwashed programmer uses them, when you're working with other folk on a big chunk of code with this stuff mixed throughout, it's easier to go along than try to mix in something else. You don't have to face down the skepticism of people who fear that the STL headers might conflict with some of Microsoft's, or that STL might add to the volume of code, or whatever...
b) Since Microsoft programmers use the kludged-up Microsoft stuff, they're NOT using STL, so problems and issues with it aren't well-known and aren't necessarily addressed by Microsoft;
c) If you don't like the Microsoft-centricity in command a and b and happen to be a Mac programmer, substitute "Metrowerks Powerplant" for the above... same remarks apply.
d) The quality of STL implementations varies widely, and doesn't seem to be anywhere near as solid as, say, the C Standard Library.
Although Stoustrup introduces STL early, uses it in his calculator example, encourages you to use it, and says, cheerfully and optimistically "the standard library and other libraries are meant to be used. Often a library has received more care in its design and implementation than a programmer could afford for a handcrafted piece of code..." this seems to be wishful thinking.
The first time I seriously used STL in a real project, I ran into a SERIOUS, SERIOUS problem with the implementation of the _map_ container. It was a performance issue. I no longer recall the type of the things I was mapping, but it completely escaped notice in debugging, because the time it took to access a map entry seemed to go up as something like the fifth power of the number of entries in the table... a few hundred entries, no problem; a thousand entries, fuhgeddaboudit. I'm talking milliseconds on maps with a hundred entries, ten to twenty seconds on maps with a thousand...
e) Because they're implemented as templates, the STL "code" itself, in addition to being very sophisticated and rather cryptic, is very hard to debug. In the example above, it was certainly faster for me to refactor the part of the program not to use maps (yeah, I rolled my own... doing a simple linear search on the keys!!!... and it worked fine) than to try to figure out what was wrong with the map.
f) Since a lot of vendors don't really do their own STL implementation but OEM it from some other outfit, it's harder to submit effective bug reports or work with technical support people on any difficult issues. And, hey, if you think it's hard to get action on a BUG, try getting action on a PERFORMANCE ISSUE. ("Sir, we don't guarantee performance..." "No, no, you don't understand, I'm talking about TEN SECONDS to add ONE key to a map..." "We don't guarantee performance...")
g) IS STL really standard? Judging from the flakiness and the rapid changes in details from release to release on the platforms I work with, I have to wonder about it... I suspect there's a chicken-and-egg problem: not enough programmers REALLY use it for the vendors to be forced to make sure it is really rock-solid.
"How to Do Nothing," kids activities, back in print!
Hello, from my own experience as a graphics engine & tools developper, I can tell you that we wrote our own core-framework for rapid application development, much like Java comes with a batch of toolkits. Up to the point where we wanted to include serialisation, our concept worked brilliantly and we had come a long way. When we then wrote container wrapper classes on top of existing stl classes to act in a COM-like fashion (in order to be able to support serialisation and interface resolving), we used the widely used stlPort version.
/m2000 option, which pumps the heap to 2000% of heap memory, things would freeze up. Since we had quite a lot of containers in combination with quite a lot of basic types, we were litteraly stuck. After STLPort gave such bad results, I tried the same with the MS version of STL but this gave us very much the same results + tons of other problems. So we fell back on our initial solution, which was to use 1 template instance of our Object* interface and define wrapper class objects for each basic type. which sucked, but it compiled. We should have tried the Metrowerks compiler which is (so I've heard) supposedly better at compiling stl than MS'es DevStudio. We'll see.
STLPort is a very decent stl implementation. Using Microsoft's Dev Studio, we could have used the microsoft implementation but it's not as compliant as STLPort, so it was the best possible option (but I still have to check out Boost as well, which offers very nice features). That said, the biggest problem with compiling subclassed STLPort classes was the compiler. In no time, template instances of the templated class definitions would fill up the compiler heap and compilation would either halt or take forever to finnish.. even if we used the
With great power comes great electricity bills.
The most important downside is that some people think that STL is the holy grail. Not so. There is no silver bullet.
The abstraction level can also be a problem sometimes allthough this is not a problem only with STL. For instance a colleage of mine had to spend much time tracking down why 1 million elements of 48bytes each consumed 144MB. I have also seen the usual problem with someone testing if a list was empty by using size()
Another downside is that the STL is a forced standard meaning that the standard was set before the compilers were able to fullfill it. It has gotten a lot better but you can still encounter limitations in all compilers.
Non-obvious limitations is also a downside. The STL has a very clean design which (unintededly) leads to a few strange limitations, such as const_interators not having a != operator
Sometimes programs using STL is harder to debug. It is not exactly pleasant to have a core dump deep inside template-template-template.....RBtree, spending some time figuring out what that is and after a few hours discover that the problem was not the container at all but something that had scribbled on a reference-copied string :-(
The STl is subject to the usual problems with "Quality of implementation". The standard is set but the implementation has been left (third-party) vendors. Why didn't the Standard Committee provide a public-domain reference implementation which vendors could optimize?
Finally, the STL some places show signs of "Design by committe". This can lead to overly complex designs or no design at all (if the committee cannot agree). Do we really need generic character support in basic_string? Which kind of bastard is auto_ptr? Where is the hash_map?
This is not a rant. I use STL frequently. STL has a lot of advantages but the poster only asked for downsides. You just have to keep in mind that there is no silver bullet.
1. It uses templates. I know the name implies this but I can't stand the way C++ implements templates. Templates are created at compile-time which removes any advantages of generics in the first place.
As compared to what language??? C++ templates are one of the best features of the language. Yes, they are a different concept, but embrace it, change is good.
I have no idea what you are talking about regarding templates being created at compile-time as being a bad thing. That's what generic programming is all about!!! Its the compiler generating classes so that you don't have to. It has to be done at compile time. I'd love to hear an example of a language that implements some kind of generic stuff at runtime.
2. While it may reduce developer time, it doesn't reduce code bloat. Templates are huge wasters of memory. This is because C++ creates a brand new class for *each* type of the template you use. So if memory consumption is an issue for you (like it is with me) then stay away.
Having additional classes only uses more memory at compile time. It makes absolutely no difference at runtime. The executable size increases only because of debug information. Stripping out the debug info will dramatically reduce executable size.
3. Template are *not* portable. Each compilier has varying support for templates. Yes the *new* compiliers support *most* of the STL but if a developer wants to get to those older models on the shelves... stay away.
ANSI C is *not* portable either for the most part. Remember, C++ is a young language with a young standard. Of course its not as portable as C, but its still more portable than any other solution (MFC, RougeWave, etc).
4. Using templates is verbose especially when you decide to throw inheritence in there. Template may look cool but they can get complicated really quickly (i.e. using the STL map template while inheriting from it)
YOU SHOULD NEVER INHERENT FROM AN STL CONTAINER. Period. There is no good reason to do this. If your design calls for it, then you have a bad design. Besides, STL containers do not have to have virtual destructors so you are introducing potential memory leaks if you inherent from them (this was made part of the standard on purpose).
5. Fragile Base Class. This is a C++ problem but it very much applies to the STL. If you build anything upon the STL and they add a virtual function... good-bye binary compatibility.
The STL does not have virtual functions. Nothing to worry about there. Remember, STL is standardized so there is no need to worry about stuff like that.
I fight extremely hard to not use the STL as there are other well-tested non-templated implementations of what the STL has.
For instance??? You are doing yourself an extreme disservice by avoiding STL.
int func(int a);
func((b += 3, b));
Tales from behind the Lagom Curtain
Also, the methods are written along the lines of, "if it's not optimal, you have to write the code yourself." I'm sorry - that sucks. Sometimes I need to remove an element from a Vector. Maybe I should be using another Container. Or maybe the API should allow it, but make it clear in the documentation that it's not efficient. I vote for the latter.
Doesn't the vector::erase method do what you want?
-- Will quantum computers run imaginary-time operating systems?
STL is a wonderful library to use for many reasons. For one, it's implemented on just about every platform I can imagine. For two, it takes full advantage of C++ templating and is a shining example of multiple inheritance done right. Having given it my praise, and suggesting that everybody use it (I do), I'll point out some things I've noticed about STL using the Visual C++ compiler, given its popularity.
.NET, that Microsoft implementation of std::string is not thread-safe. Take special caution using std::string* and dynamically-allocated strings, you will likely find memory-management hell if you do
1. Older versions of the Visual C++ compiler do not properly support C++ templates. An inspection into the MFC CArray implementation quickly reveals it is a fake template dependant on function overloads for all supported types (at least it was).
2. Up until Windows XP
3. The Visual C++ compiler complains if you include the STL headers, generating bothersome warnings about the length of the class identifiers exceeding 255 chars To stop this pest, use this "#pragma warning(disable:4786)"
4. You'll find yourself constantly trying to describe the advantages of STL over other libraries (like MFC), and use of other platform-specific technologies (like COM vs. a well-designed socket-based std::stream system), and people will start thinking of you as a hippie or something.
Aside, sometimes STL code can be a little harder to read given its semantics and use of iterators and such, which can be messy.
Stupid HTML
int func(int a);
func((b += 3, b));
Not true. You can stick pointers into the containers with as much ease as putting objects into the containers. The problem you have is freeing all the pointers when all the references go away.
I use the Boehm collector, a custom allocator, and specializations of the containers to solve that problem. If you read a good STL book, they will probably solve that problem with smart pointers.
If tits were wings it'd be flying around.
Ok, glad you acknowledge that STL has nothing to do with virtuals.
So yes, let's say you have a templated class and instantiate it for 15 different type specalizations. What's the memory overhead of this? Not much.
On top of that, if you really do have 15 differen things, how are you going to shave off that overhead using a different mechanism? Will you create 15 seperate classes intead? That's even MORE overhead than the templating. Will you create one class with a type = field? Use comparision in all functions that relate to the class with seperate paths where needed for each of the 15 different cases?
I hope you're starting to see that if you *really* have 15 seperate things, you pay that overhead no matter if you're dealing with ansi c using templates.
These are criticisms that are parroted over and over without much understanding of what's going on. Please don't perpetuate ignorance. Go test it yourself, see the results.
That's a gcc error. Some compilers do a slightly better job (I'm thinking of Visual Age for C++ on AIX machines) of formatting the errors, but they are usually about as long.
Believe it or not, eventually you do learn how to read them without much trouble.
If tits were wings it'd be flying around.
A good implementation of generic containers keeps the actual work in a hidden, non-template class. The template class -- the one which gets duplicated over and over for your 15 different things -- simply forwards operations and storage to the hidden class. And if the forwarding is well-written, most/all of it can be inlined and otherwise optimized away. Voila -- 15 containers, all sharing code.
You cannot apply a technological solution to a sociological problem. (Edwards' Law)
The number of abstract data types IN NO WAY AFFECTS CODE SIZE. Sorry to say it loudly but too many people here keep repeating that.
It may *appear* that way when working with STL but that is only because of the debugging information. Using templates will increase the amount of debug information in the executable (for each instance of the template) but it does not increase code size in any noticable manner.
Note: Ok, there are some methods that do get regenerated per-data type but the overhead is small and STL uses extensive inlining so this is almost meaningless.
int func(int a);
func((b += 3, b));
Trying to locate a bug in a program that makes heavy use of templates, and specifically STL templates, can be infuriating. Besides having your data stored in a obscure data format that's difficult to view through normal debugging commands, you've also got type names that can be hundreds of characters long. The Sun Workshop debugger used to actually SEGV on some of those long names; apparently a buffer in the debugger overflowed. (This problem was fixed a few years ago).
Hiding the implementation of complex data structures makes for easier coding, but makes life hell when you're trying to vivisect a live process. At my work, we do use STL, but in small, measured doses.
Unless you know something the rest of us don't, STL is the only option. 299,792,458 m/s isn't just a good idea, you know, it's the law.
Oh--you meant the Standard Template Library. Nevermind....
b&
All but God can prove this sentence true.
Unless there was a specific requirement and good reason for it, I wouldn't write C++ without STL nowadays. We've been using it for the last 2+ years on about 6 different unix platforms (mostly gcc2.95 over that time) and NT (using VC6.)
In that time we' ve seen a lot of improvement as native compilers for HP, and possibly IBM are catching up and threaten to replace gcc for builds on those systems.
VC6 is a real catch.. their STL implementation is only borderline usable. The solution to this was to introduce stlport into the mix, at least for our win32 builds.
Some issues we've had:
- verbose syntax (once your finger macros catch up, it's okay)
- EXTREMELY verbose compile error statements - especially when using a sufficiently complex STL object (vector of strings, or something) and doing something like attempting to use a const iter in a non-const way produces monstrosities like:
passing `const string' as `this' argument of `class basic_string,__default_alloc_template > & basic_string,__default_alloc_template >::operator =(const basic_string,__default_alloc_template > &)' discards qualifiers
(and that's a simple one.)
- Bugs on various platforms, including the lovely uselessness of VC6 STL
- Difficulty of examining data in debuggers - ddd+gdb gets a right ugly mess
- Memory High-water-marks: Some things don't really free the memory you want them to free, just hold onto it for next time. We've discovered this when we create stupidly-large temporary maps, and then delete them.
- Various little gotchas like the dangers of using remove() algorithms, being aware what map's operator[] does, etc.
- Inconsistencies between std::string and the rest of the STL
But to try and be less negative:
- STL has made handling data within a C++ program much more pleasant. For us, STL is fast and efficient, and has probably saved us many programmer-months in the debugging and development time required to use traditional C/C++ data structures. Plus, once you get into the mindset used by STL, it gets more and more powerful every time you read another part of the documentation.
If I use *vectors* to hold fifteen different types of objects, then I'll be using at least fifteen different vectors and causing fifteen different classes to be generated.
Yes, 15 different classes, but the overhead, in almost all implementations, is very very low, because each of these 15 different classes has most of their code stored in type independant storage.
For example, the map type stores it's stuff in a red-black tree. In the implementations I've seen, the map type just forwards most of it's calls into an internal object that does almost all of the actual work, and which is NOT a template, so only one copy of that code exists. These internal types aren't type safe at all; they rely on the external interface to ensure that they are used safely.
Folks complain about code bloat due to template usage but I think it's a reasonable trade-off for type safety. Especially if you were going to create all those classes one way or another anyway. By the by, for some really sick template usage, check out Andre Alexandrescu's "Modern C++ Design."
I'm trying to teach myself to set people on fire with my mind... Is it hot in here?
No they don't! A badly written example of the Vector class might require 15 different versions of the class, but numerous texts on C++ (including Stroustrup) show how to implement those as wrapper classes which optimise away to zero code size at compile time, simply putting type-changing interfaces on Vector of pointer-to-void.
Two words: Effective STL (ISBN 0-201-74962-9)
This book does an excellent job of covering the strengths, weaknesses, and pitfalls of using the STL.
Among the STL's (and C++ standard library's) deficiencies are lack of generalized functors, hash containers, smart pointers (the only type included, auto_ptr, is not very useful), and thread libraries. All these and more are addressed by third-party libraries such as Boost (boost.org) and Loki.
All these features are under consideration for inclusion in the next C++ Standard (C++ 0x) being worked on now. The Boost libraries in particular are strong candidates for inclusion in the next Standard; if not, something very close to them should be in there.
Democracy is two wolves and a sheep voting on lunch.
>The fact that no compilers support all of STL is admitted by Stroustrop (sp?).
Hmm. Perhaps you are refering to his remark
that no C++ compiler supports the export keyword?
This keyword is not necessary to use the STL,
and at least one commerical compiler now implements it.
Or perhaps you are refering to his remark that not all compilers support member templates and partial specialization. Perhaps true at the time he wrote the book, but no longer true. GCC and many others do support them. MSVC 6.0 does not.
Why did you post this excellent and informative message anonymously? I love "deferred addressing" and "metacircular allocation"...
Karma: Good (despite my invention of the Karma: sig)
YOU SHOULD NEVER INHERENT FROM AN STL CONTAINER. Period. There is no good reason to do this. If your design calls for it, then you have a bad design. Besides, STL containers do not have to have virtual destructors so you are introducing potential memory leaks if you inherent from them (this was made part of the standard on purpose).
I respectfully disagree. Often I want to write my own container class that's based on an STL class (let's say a vector). I want to expose some of the methods, but not all of them.
One way to do it is to have a vector instance be a member variable. But if you want your class to support iterators, then you have to write your own iterator class. Writing STL-style iterators is, in my opinion, an enormous pain in the ass, involving lots of tedious coding.
Instead, you can use private inheritence, and just expose the methods of the base class you want (including the iterator) with the using keyword. There's no need to worry about virtual destructors because you're never going to provide the users of your class a pointer to the base class: the inheritence is private.
In other words, you can do something like this:
class MyIntVector : vector < int > {
public:
typedef vector< int > base;
using base::iterator;
using base::begin;
using base::end;
using base::operator[];
using base::size;
};
If you're never going to give the user a pointer to the base class, then what's the harm in deriving from an STL class? Seems to save a lot of typing to me.
-- Will quantum computers run imaginary-time operating systems?
Your comment points to what I think is THE major downside to STL: debugging.
If something's not compiling that you think should, you end up wading through the mile-long error messages. If it does compile but doesn't work right, you're going to find yourself in the debugger trying to step through some of that crazy obscure STL C++ code to try to figure out what the heck is going wrong. Neither is much fun.
But when it does compile and run correctly STL is pretty nice!
I'm looking forward to somebody starting over some day and coming up with a language that supports generic programming as well as C++, but which doesn't have the terrible syntax of C++ templates. It must be possible.
Basically people have realized that templates can can be used to create programs that run at compile time to do some very clever optimizations (template meta-programming is what they call it see http://www.boost.org for one implementation. Blitz++ is the big example use of the stuff that everyone points too). But the code to make this stuff happen is ATROCIOUS!
Yeh, you can make a template meta-program to calculate factorials at compile-time. Great! That sort of thing can come in handy. You can even write template meta-code that basically generates code at compile time. That's cool too! But the code to do it looks NOTHING at all like the equivalent run-time code. Why does it have to be that way? Why does compile-time code have to look SO different from run-time code, at at the same time look SO horrific?
I think what is needed is a new language that will put compile-time and run-time code on equal footing. It would be great if they had the same syntax. Then you could just, say, change one line to turn some run-time code into compile-time code (only when there's no dependence on run-time data, naturally). But it doesn't necessarily make sense to put all the run-time efficiency restrictions on the compile-time language. Dynamic function lookup by strings is a pretty big run-time hit, for example, but you wouldn't care as much if it were used for compile-time function lookup.
In general, the meta-programs seem work a lot more like functional languages -- so fine, I'd be willing to settle for at least a clean syntax for the compile-time language, say something Lisp-like, even if it looks different from the run time language. ANYTHING, as long as the syntax is clean and readable, would be better than the current situation of trying to do meta-programming in C++.
I think the situation C++ is in today with respect to generic programming and meta-programming is a lot like where C was when OOP started to become big. People realized that, yeh, C can do OOP, but it doesn't really support it. C allows OOP, but it offers nothing really to facilitate its use. I think Stroustrup makes that argument in his C++ book. So Stroustrup created C++ as a language that would support OOP, not just allow it.
Well folks, now we've got this handy meta-programming stuff, and yeh you can do it in C++, but it is not pretty. It's downright painful. Writing it is hard. Debugging it is hard. Testing it is hard. Reading it a week after you write it is even hard. Sounds to me like it's time for some new language stud to come and save us.
STLPort claims to have the best conformance and best performance. Performance shouldn't be that much of an issue, since you would probably use the stl container and if it wasn't fast enough you would write it yourself.
Also STLPort's error and warning messages are a whole lot better than other implementations.
Sorry, no. If you're working with multiple DLL's and you access a std::list declared in some header from both of them, functions that you call in both DLL's will be located in both DLL's Thus code bloat. For a monolithic application, you are correct.
YOU SHOULD NEVER INHERENT FROM AN STL CONTAINER. Period. There is no good reason to do this. If your design calls for it, then you have a bad design. Besides, STL containers do not have to have virtual destructors so you are introducing potential memory leaks if you inherent from them (this was made part of the standard on purpose).
That's a pretty broad statement, and again I disagree. Suposing you want to create a string class with a subset of the functionality in std::string? Do you re-implement it? Supposing you want to create a structure that is best expressed as a list, but has just a little more functionality? Granted, you have to keep a pointer to the derived class, because of the virtual dtor issue, but its not completely unheard of.
Jherico
What can the average user can do to ensure his security? "Nothing, you're screwed"
Uhhhh.... huh? The string class is like any other class is like any other critical piece of data. Protect them against multiple accesses.
Here's what the status is for GCC 3.1: http://gcc.gnu.org/onlinedocs/libstdc++/faq/index. html#5_6.
It works fine in my multithreaded Linux apps.
You cannot apply a technological solution to a sociological problem. (Edwards' Law)
the syntax and readability are so horrible that it took several computer scientists years to decide exactly how butt ugly and unreadable to make it.
STL is not, in any way, shape, or form, a step forward for programmers.
people can write stuff with it that is totally incomprehensible to anyone who is not party to their school of programming style -- but this is true of C and C++ in general.
I don't know what the solution to programming's difficult problems with reliability, reusability and maintainability, but I think Java has done a lot more to improve the state of the art in programming models, especially WRT these problems, than the STL.
Treatment, not tyranny. End the drug war and free our American POWs.
See my user info for links.
In practice, the big problem with the STL is that Microsoft doesn't like it. It's one of those standards that Microsoft doesn't control, yet is so widely used that they can't ignore it. So they support it, but badly. (OpenGL gets similar treatment. So does C++ itself. Microsoft prefers their own dialect of C++, which is not fully compatible with the ISO standard.)
The STL doesn't help too much with the big problem of C and C++ programming: keeping track of who owns what. auto_ptr and the STL don't play well together. That's a lack, and it's not easily fixed. There have been three iterations of auto_ptr semantics, all of which have some painful problem. See "comp.std.c++" for discussions on this subject.
> what are the downsides to the STL?
These aren't really downsides, just things to remember while you're using it:
* it's not inherently threadsafe - remember to lock if necessary!
* as somebody else as pointed out, choose your templates carefully for maximum performance (Meyers' book is good for this)
* if you're doing cross-platform stuff, build on the target platforms on a regular basis so you find differences early and have to change a minimum amount of code
Stroustrup's Third Edition has some STL stuff...Meyer's book is good if you know the basics and want to expand your knowledge (kinda along the lines of his C++ books).
LOL
moded as interesting but plain wrong.
but there is a lot of overhead with using the STL.
No there is no overhead in terms of speed. The STL is designed to yield as efficient code as a VERY GOOD coder would get by hand coding. As the STL is coded with "how will the compiler work on this" in mind its often far more efficient than hand crafted code ever will be. (e.g. inlining over several function calls in depth)
Virtual functions and things of that like can make your code bigger and slower.
In the STL there are only few virtual functions. Most are non virtual.
Also a non virtual call costs you about 8 bytes asuming a 4 bytes instruction and 4 bytes adress, where as a virtual call you cost about 16 bytes, load register with adress, two times 8 bytes and jump idirect with register and offset, again 8 bytes.
However in practice the latter case is often only slightly bigger than the former(depending on the instruction set of the CPU).
If the code will be bigger than without STL is a question how your compierl and linker treat templates.
And it is a question how you would replace templates by hand.
Regards,
angel'o'sphere
Cost free eBook I read (by iBook/Kobo/Amazon/ObookO/Gutenberg etc.): "The Green Odyssey" by Philip Jose Farmer.
C++ templates are one of the best features of the language. Yes, they are a different concept, but embrace it, change is good.
They are no different than a majority of languages out there. Remember that C++ got it's roots from elsewhere.. C++ is anything but different and original. Change is not always good.. especially when the implementation is bad, IMO.
I have no idea what you are talking about regarding templates being created at compile-time as being a bad thing. That's what generic programming is all about!!!
No sir. Generics should be resolved at run-time as much as possible (that is why they added RTTI to C++). With templates being done at compile-time it removes my ability to extend my Linked List to use basic_string and ints without adding yet more code. Templates suck at being generic, especially when you want it at runtime.
Its the compiler generating classes so that you don't have to. It has to be done at compile time. I'd love to hear an example of a language that implements some kind of generic stuff at runtime.
Smalltalk, Python, Dynace, Objective-C and even C... all nice languages
It makes absolutely no difference at runtime.=
I beg to differ. *every* template you instantiate adds to the binary size because of the need to use them. If I create a vector<string> and vector<int> I get *two* vector class and it will increase the binary size accordingly. Another downfall is that you can't mix and match types, so you have to encapsulate your nodes in yet *another* class... adding even more to the binary.
C++ is a young language with a young standard.
Even more reason not to use it!! the STL is *not* standardized, check your implementations.
YOU SHOULD NEVER INHERENT FROM AN STL CONTAINER. Period.
I disagree. You want to extend an STL containter to create better ones.
Remember, STL is standardized so there is no need to worry about stuff like that.
STL is *not* standardized...
For instance??? You are doing yourself an extreme disservice by avoiding STL.
hmm.. wxWindows, QT, Gtk+, Plib, and any other library that wishes to be *portable*. IMO, you do yourself a great disservice for using the STL.
--seaBut templates increase code size as the compiler has to genarate a different version of the class for each unique instance that you use.
i
e. If you use a Vector to hold 15 different things, the compiler has to generate 15 different version of the Vector class to compile your project.
Right but wrong.
I think you won't use vectors of Objects but vectors of pointers or vectors of references, right?
So all "instances" which the compiler is generating are the same in terms of cpu instructions.
A good compiler/linker sees that and removes the duplicated code.
Again, the question I allways ask: if you would do it by hand, how would *you* do it? Writing a List_of_Strings class and a List_of_Persons class?
And that does NOT duplicate code?
The STL takes care to use sophisticated inheritance, template specialization and delegation to derive special cases from common abstractions.
The more you use the STL in one single project the less code is added for ech additional application of the STL, as it is likely allready included somewhere else.
Regards,
angel'o'sphere
Cost free eBook I read (by iBook/Kobo/Amazon/ObookO/Gutenberg etc.): "The Green Odyssey" by Philip Jose Farmer.
Others have already pitched the positives, so here are a few of the negatives. There are a couple of things that I see as real problems with the STL. Having just gone through a small-scale STL development project, I've come away with a really bad taste in my mouth. Here's why.
With the STL, C++ has finally aquired a part of what Smalltalk and Java have always had: a library of base classes. With these sorts of capabilities, you tend to start thinking about your system in more object-oriented terms. This is a good thing in itself, but C++ just doesn't go there with the ease that other languages do.
For example, the OO notion of polymorphism goes completely against C++'s strong typing (and C++ is even more finicky in its type checking than C is). In a true OO system, I don't care what kind of object I have in my hands, I just care that it does a certain thing. This is where late-bound OO languages like Smalltalk and Objective C shine.
Also, as your project progresses and you factor your code into neat little objects, file-based source code navigation becomes a real bear. IDEs like Source Navigator can help with this, but you still have to do double-entry bookkeeping for your prototypes and function declarations.
Why didn't we see these problems before the STL? Because we never tried to use C++ as much more than a superset of C. With the STL, we had the opportunity to build things that were more like our other OO systems, so we did. And that's where we started to get bogged down.
One other thing: We had more discussions about coding style in a few weeks of STL coding than we ever had in our non-STL C++ coding. Perhaps that was because more of us were involved in the project. But I think that, at the heart of it, the STL gives some people a feeling that C++ code can has a chance of being "elegant", and there is a real tendency to push yourself to try to achieve it. Without the STL, we all just knew that C++ was bubble gum and bailing wire. It happened to get the job done for us, and we didn't bicker about style.
Perhaps your situation is different, but if I had to make the call, I'd say your time might be better spent learning something else.
I tried to buy into the whole thing. I jumped through all the hoops to use the predefined function objects (plus, minus, multiplies, etc) with the non-mutating algorithms (for_each, find_each, etc) and function adapters (bind1st, bind2nd, etc).
::iterator.
My god, that stuff is WAY too verbose. It's almost always more straight forward and less error prone (debugging those syntax errors from the compiler messages _sucks_) to go straight for a standard for loop using the appropriate
Or can the majority of English-speaking humans not spell "rogue" or "lose" properly?
Cheers,
Backov
In the law there is no overlap between theft and copyright infringement whatsoever.
"Both the Solaris (actually SGI) and RogueWave implemementations DO NOT match the documented interface, even though Rogue Wave's documentation says it does! So make sure your intended usage is actually supported by the implementation of the STL that you're using."
Uhm, last I checked, that's because Micro$oft doesn't implement the STL standard properly, and their MSDN docs reflect their implementation, not the standard one.
Maybe this has changed, but I doubt it. For a much better (and correct!) STL reference, go see dinkumware, which sells an online reference, as well as a complete library implementation, should you need it. Dinkumware, conveniently, also provides the online docs over the web for free, as long as you promise not to download them to your machine.
Let's try not to let fact interfere with our speculation here, OK?
The main draw back is the learning curve.
... and fun, into the development.
Probably there is a further one: getting your team mates as enthusiastic as it is needed to get progress and benefit
The most serious drawback however is:
o buggy STL implementations shipped with compilers.
o buggy compilers not able to work with more sophisticated STL versions
o code generation bugs during inlining or partial template specialization
o probably a weak support by debuggers
The reason why I switched to Java is not that it is a superior language or is in any way cooler like C++, but I worked from 1993 to 1997 exclusively with C++ and nothing sophisticated I wrote compiled on more than wo compilers.
The C++ manufactors are to fast out of market if the platform is Windows and seem to have so much trouble staying in business that they need 5 years or longer to adapt a standard.
OTOS are "pirates" like Rogue Wave who have several libraries to sell and suddelny they port all libs to use STL below them and force the customer to buy sTL also.
Besides that their STL was for a long time the buggiest and so incompatible that you could not replace the "bought" STL with a different free version.
(I'm speaking about Tools.h++ and the change of RW Tools.h++ to use RW STL later)
Regards,
angel'o'sphere
Cost free eBook I read (by iBook/Kobo/Amazon/ObookO/Gutenberg etc.): "The Green Odyssey" by Philip Jose Farmer.
C# sounds like an interesting exercise, if it supports all the things they claim. And best of all, it has an actual standard to its name. I must learn this language next.
-
I'm calling your bluff. Give me some stats for example programs.
Our company has to switch between two different implementations to compile between MSVC for a Win32-based build and MS Embedded C++ for a WinCE-based build.
Instead of hacking around with two different Microsoft STL implementations, why not standardize on the cross-platform, open-source STLport? It is very complete and has helpful runtime assertions. My only complaint is that debugging STLport is difficult because of its impenetrable naming conventions..
cpeterso
If you're never going to give the user a pointer to the base class, then what's the harm in deriving from an STL class? Seems to save a lot of typing to me.
Your playing with fire there pal... Instead of using inheritence, just simply return a vector iterator from a private member. Works just as well. Besides, the users going to have to static cast the reference in order to get to your methods. That opens the door to storing off a pointer, and subsequently, deleting the base pointer.
I understand your point, but its just bad design. The problem is that this is a bug that most people wouldn't recognize so your really taking a gamble.
int func(int a);
func((b += 3, b));
Check out BD Software's free message decryptor: "Freeware with Source Code, supporting: Comeau C++, g++, VC++6, VC++7 (Visual Studio.NET) and Metrowerks CodeWarrior"
www.bdsoft.com/tools/stlfilt.html
The messages are still a bit odd until you browse the class which triggered the error, but it shortens them down to a readable, meaningful length.
I'm a fairly recent STL convert and I find this tool utterly invaluable. I love STL because it provides a true standard for many of the structures and algorithms that are core to any project. I'll never have to deal with another crackpot programmer's homegrown, poorly commented dynamically-sizing array class again.
Learn who owns what. Learn how to handle pointers and references in an intelligent manner. Garbage collection is neat but is no substitute for good programming.
Read Those Fine Manuals. See SGI STL Tech Pages for a good online STL reference. Pay particular attention to stated efficiencies. You can use an iterator to loop through any container, but not all containers are created equal.
Get a good compiler. Template and inline code bloat can be minimized by selecting a decent compiler and flags.
You can use things like for_each, but remember you can also use a standard for with iterators.
So, is RougeWave a C++ SDK for designing makeup, or what?
"It sure was strange to see something on Usenet about me that didn't involve Klingon gang rape." -- Wil Wheaton
Besides, the users going to have to static cast the reference in order to get to your methods.
No, they don't. The "using" declarations bring the methods into the scope of the derived class. Absolutely no casting is necessary.
I don't like returning a vector iterator, because then people who use the code have to declare their iterators of type vector::iterator, rather than MyClass::iterator. So, if I change the underlying representation, all the clients have to change their code. This, in my opinion, is worse.
-- Will quantum computers run imaginary-time operating systems?
Just wanted to point out that the STL is not, in any way, an OO system. It uses classes, but that's as close as it gets. There's no use of inheritance, polymorphism (in the usual OO sense) or any other "typical OO" features.
If you disagree, post your argument. (-1, Overrated) isn't your personal censorship tool for views you don't like.
Watch out for these:
1) old compilers. Sun CC 4.2 used to have a templates DB that didn't work well with incremental builds.
2) costly to copy objects that need to be stored in containers. you can store pointers instead and manage the object lifetimes yourself or a better thing to do is make those objects ref. counted with "copy on write" semantics
3) you will need your own thread synchronization if your containers/the objects in your containers are not read-only. see http://www.sgi.com/tech/stl/thread_safety.html
prasad
Why not declare iterator as a typedef in MyClass?
typedef vector::iterator iterator
Hey, that's pretty clever. Somehow, I hadn't thought of that.
-- Will quantum computers run imaginary-time operating systems?
It's kinda like C in the late 80's, before ANSI C really took hold. Too much wiggle room for the compiler vendors, and no best practices established (that would later be ratified by a spec).
PHEM - party like it's 1997-2003!
The drawback of the STL is that debuggers do not
know about it yet, for the most part, and show
you the implementation of the STL objects instead
of their semantic values.
Dev elpizw tipota, dev phoboumai tipota eimai lephteros http://euclidian.org
Now, isn't the point of encapsulation and abstraction that you don't need to care about the underlying implementation? Having a library where you need to (for all non-trivial applications) just defeats the purpose of all that complexity in the first place.
/Janne
Trust the Computer. The Computer is your friend.
If you are a good computer scientist there are no real downsides. If you are just hacking a system together and don't understand how the datatypes and algorithms work, and you don't have time or care to read the manuals, you will be in trouble using the STL.
I have used several versions of the STL on several compilers and OS's, and find that as a whole, the STL has few downsides, **IF YOU READ AND UNDERSTAND WHAT IS GOING ON** If you don't understand the basics, it becomes a nightmare to debug. On the flip side, if you understand what is going on you can get very fast code at low development cost.
Developers need to understand that certain operations invalidate iterators, and things like that. (That is the most common error that I see.) When you get an error in STL code, usually it shows up not as a single error but as a huge list of errors as it propogates through the template library -- but it is just one coding error. You might consider those as downsides, but they are typical in computer programming.
A lot of people listed 'bugs', slow learning rate, and other problems, but in my experience the STL is easy to use if you consider the two aspects the STL covers -- data types and algorithms. I have seen other programmers struggle because they cannot separate the two. They think that string types should have string algorithms in the class, or sets have the set operations, and so on. The STL is an attempt to keep the two apart. It is easy to write new data classes that use the STL by implementing the few functions needed for all the algorithms, and it is easy to write new algorithms that use any STL object because they all implement the same small set of functions.
One example -- It is easy to change the allocation method (swap portions of ram to disk) simply by writing a new allocator. A co-worker insisted that the STL wouldn't work outside of RAM, but a simple allocator class allowed everything to work on disk for huge data stores. The co-worker had spent years working on implementing a few slgorithms and data types on his own. The STL with a simple, custom allocator worked faster than his code, and took much less time to develop. Poor guy -- I really felt sorry for him.
There are some problems with specific older compilers, but most are fixed. The older Metrowerks compiler didn't allow traits, the older Microsoft compiler didn't allow several kinds of nested types (use the service packs to fix them) and their debug info is terrible in VC6, GCC used to generate very bad STL code (it still has some quirks). The glitches are mostly fixed now. New, GOOD compilers will take longer to compile (downside) but will often generate either smaller code or significantly faster code (big benifit). I have seen cases where the executable doubled in size (the code bloat that people talk about), but the runtime decreased signficantly (not usually mentioned), and the code became much more readable. Since most of us (except embedded systems people) don't need to worry about size, the tradeoffs are acceptable.
Another benefit/downside is that if you use optimizing compilers that know about the STL, you can do really incredible things. For example, if you are using a valarray (value array) type to perform operations, you can get massive speedups. I use the Intel Optimizing complier for x86 chips, and it uses MMX, SSE, and SSE2 optimizations to perform many loop, array, and STL operations. It is cool to see huge sections of code the the compiler message "foo@bar@PARAM@Z has been selected for automatic CPU dispatch", and reading the generated code shows that it uses the MMX or XMM registers, depending on the CPU type, or use the slow, loop based values on 486/Pentium chips. A bad compiler would probably just go to the worst case, the slow loop -- so get a good compiler.
Itanium chips could do extremely well on many of the STL algorithms. (I have wondered if the Intel Optimizing compiler for Itanium would do massivly parallel ops with valarray classes. Does anyone have experience there?) Other parallel chips can benifit in this way as well, IF THE COMPILER IS SMART ENOUGH TO DO IT. The downside is that you have to know how things work and why. If the compiler doesn't do the optimization, perhaps another algorithm would work better in that case.
//TODO: Think of witty sig statement
Compare just about any use of C's qsort with C++'s std::sort. The fact that the latter is implemented as a template means that any specialised comparison functions can be inlined and optimised right in the sort algorithm, unlike the mandatory level of indirected required by qsort's call-via-pointer approach. I don't have any timings handy to give entirely objective evidence, but I've certainly done rough-and-ready timings on several compilers, and all the recent ones had std::sort way ahead. A quick glance at the generated assembler confirms the theory above.
If you disagree, post your argument. (-1, Overrated) isn't your personal censorship tool for views you don't like.
You were trolling here...
There is a need for a continum of tools. The fact you are part of the "everyone" who seems to think that a language must be all things to all people is, well, kind of a poor reflection on you not the language.
There are PLENTY of things that C++ isn't "the best choice" for. Primary among those are the projects where you just want to slap something together safely.
The fact that I wouldn't let most people near an industrial band-saw doesn't somehow invalidate the existence and purpose of that device. Yes, people who don't know, or don't care, to learn how to use equipment properly should be laughed at when they get themselves hurt. People who decide to go SCUBA diving withtout training and get themselves killed also deserve what they get.
People who jump into C or C++ without the necessary foundation in "real"(tm) (8-) programming will hemmorage memory and dump core and generally make all sorts of messes. Shame on them and pitty to their employers and all that.
Still, a skilled craftsman with C/C++ can and do make better, faster, and more effective code than an equally skilled craftsman using the safety-net filled scriptirrific languages.
Why do you think Perl and Python are written in C/C++?
[rant]
And to diverge into a rant some, Python is a screwup waiting to happen. Friends don't let friends use whitespace as a control structure. I officially consign anybody who advocates using Python for real work to RPG hell for the rest of eternity. replacing the two characters "{" and "}" with the one character ":" and needing to worry about counting spaces/tabs is no bargan. Yes there are editors that will help you but now your language is dependent on your editor and code that reads identically on paper may do different things in the computer. How dumb is that?
Anybody who recomends Python over C++ because C++ is a "bad" language but Python is a "good" one knows nothing about language theory (spoken or computer languages)
[/rant]
Innocent people shouldn't be forced to pay for inferior software development.
--"Code Complete" Microsoft Press
The biggest advantage to the STL is that it isn't RogueWave :-)
Of course, nothing in life is perfect, and STL is a prime example. But it's advantages far outweigh its warts.
A Government Is a Body of People, Usually Notably Ungoverned
However, C++ as it exists today (notably including all of the standard library stuff we're discussing here) was only really defined by the standard in '98. C++ has evolved and grown for a couple of decades, but it's hardly the same language today as it was in the early '90s, say.
If you disagree, post your argument. (-1, Overrated) isn't your personal censorship tool for views you don't like.
It's not "C++ STL", it should be "C++ ST,L", which stands for "C++: Suck This, Loser". (At least that's what the compiler's error message says, if you manage to read between the lines... I think this post will prove the point.)
Those compiler guys really have a weird sense of humor. IT'S NOT FUNNY, YOU HEAR ME??!?
Bastards.
Unfortunately, that is what I meant. I used a sed script to replace string,and>>> with string, etc. That helped for the common problems, but debugging was a big problem - especially being unable to directly view the contents of data structures in a useful fashion. Suddenly, I had to create .debug_print functions for every single class...
..it's not too great.
Implementations across platforms aren't always the same and g++ older than 2.95 doesn't support a bunch of stuff like streams and such.
Also, the strings lack many obvious operators such as string(int) which makes STL a pain in the ass for me.
My recommendation? For projects who can stand using a GPL'ed library, definitely Qt/E. With the right config you can compile it in well under 1MB and QString, QMap, QServerSocket, QSocket are all wonderful.
I disagree with your disagreement. Ask yourself this: why do I want to derive from the string class? Is it because you have a new function you will be adding and every other string method is still necessary for your derived class? Since string has methods for several diffent uses, it is unlikely you actually need everything that it implements, and creating a new class with that broad set of functionality (via inheritence) is bad programming practice because you have given your class more functionality than it needs. This is even more true for a list class. I'm sorry, but I can't imagine a situation where every single list method is required.
Just create a new class with the same methods that you needed from the old class and add the new ones to it. You can also put in copy constructors and conversion operators that allow interoperation between your new string class and the old one easily enough.
After all, did the designers of STL say, "boy, we like this vector class, let's derive a list class off of it to save some work"? Nope, they reimplemented using many of the same method names and styles since they didn't need polymorphism between the two classes, just mental model-sharing.
personal attacks hurt, especially when deserved
Perl has never been such. It is a general purpose programming language used for such varied tasks as image manipulation, scientific computing, database management, and an army of other tasks. Its "standard library" is perhaps the largest such in the industry. Have a look at the official module list on CPAN.
Perl may be used as a "toy language" by many, but do not assume that that makes it a toy.
Perl6 is a re-design from the ground up, which is in many respects to Perl5 what Perl was to scripting languages. It introduces a real object model that takes the lessons learned and best practices from Perl5's very loose "roll your own" object model. It also retains all of Perl's power while focusing on the problem of creating a back-end that can be efficiently compiled or executed as byte code in Perl's own virtual machine ("Parrot", as it's known).
If you've ignored Perl because it looks scary, go back and try it again. You will be suprised. Very.Go look at that module list. Think about what it means to be able to think "hey, i'd like to..." and find that it's in the standard library! Now imagine how those of us who program in truly high-level languages like Python, Perl, Ruby, etc must feel when we have to "step down" to commercial languages whose standard libraries are controled by committe.
Only problem with java is of course the JVM...though I hear inroads are being made on native compilation, they're still not up to par with C performance.
I would like to see something with native performance combined with the syntax of java. It's not perfect syntax, but its a vast improvement over that of C++.
I hear C# delivers much of this though.
-
That's object files, not code. Code is what a developer writes. If a developer doesn't write it, it's not code; it's a build product.
Having a larger build product can be problematic, but it is nowhere near as problematic as having to write more code. The trade-off you make with Java collection classes, trading compile time safety for a smaller build product, is in almost all cases a bad one. A smaller build product means that you can run on a machine with fewer resources, but compiled code is almost always only a small fraction of the resources needed in an application. Usually, an application uses nowhere near as many resources as are available anyway. However, compile time safety translates to fewer developer hours spent debugging, and can often lead to faster code. It is almost always better to opt for the compile time safety.
That said, I develop almost exclusively in Java right now. Java is a great development kit, but it will be a much better one when we get templates in JDK 1.5.
Like any other technology, the STL has several upsides and downsides. Since I didn't see many negative comments, I'm going to address some of the problems I've encountered using the STL.
My experience has been primarily writing and porting code in the UNIX environment, so keep in mind that I am fairly ignorant of the state of things in the Microsoft world.
The most obvious downside to using the STL is that the generated object code ends up being rather large. This is primarily due to the inlining of member functions of templated classes. While most developers don't really care about this type of thing, it does become a rather significant concern in the embedded world.
Another rather large problem with the STL is that some pieces of the library interface are rather inconsistent with each other. Some of the container classes throw exceptions, others don't. You may not think of this as a serious problem, but consider the following:
Steering ourselves away from exceptions for a couple of minutes, let's tackle the subject of inheritance... First the STL container class don't get along very well with class hierarchies; what I mean by that is that the following is a mistake:
The rational as to why you can find in Scott Meyer's book Effective C++ . The short explanation is that an array of classes can not be properly treated polymorphically. I highly recommend that book to anyone looking to either write C++ or designing a program that will be implemented with C++.
Another issue that can crop up and bite you is that of memory management. The auto_ptr helps a lot with this one, but you must be careful with any non-intrinsic datatype that you store in an STL containers.
A couple other random things to consider:
The STL is a fantastic programming tool if used correctly, however there is a steep learning curve and quite a few gotcha's. I hope some of my thoughts help.
Aside from the debugging nightmare (much improved by tools such as STLFilt, BTW) and the portability issues, IMHO the biggest problem with the STL at present is the lack of glue to take best advantage of it.
For example, there is auto_ptr but that's incompatible with the standard library container classes. Instead you need to head for something like Boost to plug the gaps.
Similarly, you have all these fabulous algorithms that take optional predicates, but then you start writing rubbish about binders and less<int> to get them to do anything useful. Again, the answer is perfectly possible (check out the various expression template libraries in circulation), but relies on a good level of template support in C++ and isn't (yet) standard.
Fortunately, the next version of the C++ standard should address these shortcomings and plug the gaps, at which point the C++ STL implementation will become one of the most fabulous libraries in existence.
If you disagree, post your argument. (-1, Overrated) isn't your personal censorship tool for views you don't like.
Actually, the sorted containers are implemented using red-black trees. Hash tables are not used in the sorted containers because the performance of a hash function can't be guaranteed.
Iterating over the leaf nodes is the same cost as iterating over a list. Finding an element with a known key value is logN for the sorted containers while the same operation in a list is linear.
It's pretty sad that not a single C++ compiler supports STL 100%. I believe that if there isn't code on the shelf (or ftp server, take your pick) that no standard should be based on this.
The equiviliant is the EPA saying that all cars should get 150 mpg. Few if none will. It only makes the EPA look bad. (Look, we've got the best standards in the world!!)
Pan
Forget all you've heard about extreme programming... I'm writting a book called The Art of WarProgramming.
I said no... but I missed and it came out yes.
I just wanted to point out that asking about something like the STL here on /. will not give you much breadth of opinions on the matter. When it comes to programming and software development, /. has a high concentration of scripting language users for web site backends and administrative tasks, and a relatively small number of "application" developers. There are also a disproportionate number of systems programmers. From reading /., you might get the impression that C++ is not very widely used. While this is true in the Open Source world where there are many *many* more viable options, commercial software development is still pretty dominated by C++ with Java seeing use in some sectors. So what's the takehome message here? Even given /. bias, you're still getting a pretty positive response to STL. Anyway, here are a few things you should know:
1) Get STLPort. Use STLPort. STLPort addresses many, many, STL issues. They add extra nice classes like hash tables. STLPort is thread safe. STLPort has nice extra debugging features. STLPort has readable code. STLPort is PORTABLE (thus the name!). OpenOffice uses STLPort, in case you're still dubious.
2) Get a couple of STL books. There aren't any really good ones (IMHO), but it's handy to have a printed reference with some examples.
3) You wanted downsides, so here's one. You will have to learn STL. Not the library, but the techniques--the API is easy. You have to write your own C++ classes well to take really good advantage of STL. The way you leverage the STL for absurd productivity is through generic programming and STL's pluggable component architecture. Still, though, even you all you ever use is map, string, and streams (or some other subset), you'll probably become a convert.
4) STL will keep getting better to use. Other people have mentioned it, but look at Boost for some ideas about where STL is headed. Also, the compiler people are aware of and are working on the error message and debugging problems. Both VC++.Net and gcc 3.x are making progress here.
forget for a little moment about being enforced to templates in C++ because of a missing general base class (like Object in Java).
Er, I can cast to (void *) in C++ just as well as I can in Java. That doesn't mean that I want to.
(heck, you could even "typedef std::list kool_list" in a header and be done with it)
Daniel
Hurry up and jump on the individualist bandwagon!
g++ is just what i needed for a fun and relaxing weekend of random hacks.
I was goofing off with a trivial c++ hack that provides a base64 iostream iterator. I've heard for a while about the relative bloat and performance hits on the IO side of c++ and wanted a peek for myself.. what I found was halting.. 50x performance increase from a simple C hack, all of it IO. Well, not to be defeated so easily, I plugged in STLPort with its spiffy optimized IO and gave a whirl. What resulted was not 1:1 with C but reasonably in the realm of hand tunable for IO buffering thereafter... this was after all, code that reads and writes a byte at a time vs. a c program that uses buffers...
the relative results of this effort were as follows: test were conducted streaming 1 meg of data to >dev/null on an athlon 1800xp under debian sid dist.
buildtimesize
gnu uuencode, from gnu sharutils, compiled c code. ~0.12 seconds/meg binary 9k
base64.h: using g++-3.0.4 -O6 -static
~3.5 seconds
binary size 895k
base64.h: using g++-3.0.4 -O6 (shared)
~4.8 seconds
binary size 6k
base64.h: using g++ and stlport -O6
~0.45 seconds
binary size 10k&7k, static and shared.
Deriving from string is perfectly valid, although it's better to derive from basic_string which is what a string is anyway...
For example, we have a string class that add a 'printf' member function. The other way to do it would be to have a global function that takes a string, which is a far worse option.
What about the need for an 'exists' function in map classes? Sure, you can do it in a couple of lines of STL but if you've got 1000 of those then it gets real tedious. Simply derive a new map and use that & problem solved.
The STL *is* part of the C++ language.
Anyone claiming to know C++ who doesn't know the STL is lying.
http://www.elis.rug.ac.be/~brdsutte/squeeze++
you can see that we are able to reduce the code size of real-life programs (e.g. LyX) using a lot of templates by 60%. This is done by compacting the programs after they are linked, applying aggressive whole-program optimization and code abstraction techniques. There is a specific manuscript on the page as well, on how to reduce the code bloat coming from the use of templates. An important technique is whole-procedure reuse: if several identical procedures are found at the assembly level, no matter what the source code was, the duplicates are eliminated from the program. If similar procedures are found (e.g. in sorting routines where only the called compare method is different), they are merged using a new parameter.
Cheers,
Bjorn De Sutter
Ghent University
Close. The goal with abstraction is that you can usually swap one object for another with a single change to the source file. You shouldn't have to make any other changes in the source code. You choose the object precisely because of the different costs of different types of operations.
This is much clearer in Java than in C++, since the interface is distinct from the class that implements it. E.g., in Java I can specify that I want a "SortedSet" interface (which describes the operations that are valid on the object - and which isn't easily changed), and the constructor specifies that I want it actually implemented with a "TreeSet."
For every complex problem there is an answer that is clear, simple, and wrong. -- H L Mencken
I've never seen a library of any kind that couldn't be used hard without eventually having to look at (or wishing you could look at) the source. Since the source for STL isn't comprehendable by anyone short of the people who wrote it (perhaps not even them), I would be very reluctant to use it.
In fact, I have been working for over a year on a project that I didn't write that is part in VC++ and part in Borland C++ (don't ask), and STL has been a real headache for me.
As long as it works, I'm fine, but debugging it, and sometimes even working out the header file dependancies is horrible.
I'm of the category of folks who uses a home-grown container library that is easier to use and more consistent than STL, at the expense of some flexibility, some performance, and a whole lotta obfuscation.
And yes, I use macros in a templatey way, but it's totally portable, has full type checking and is reasonable to debug.
My advise is take some non-trivial time to educate yourself or you may make a decision (for or against) that you will come to regret later.
You are in a maze of twisty little passages, all alike.
Well, you don't care about the implementation. But you do care what kind of operation you are performing. You don't really want to "encapsulate" away that you will perform a linear time lookup instead of log-time lookup when you use a list versus a set.
Think of them as different operations that one container supports and the other does not.
Are you using a pre-STL version of Tools.h++?
The STL is vastly superior to the old Tools.h++
template collection classes. The STL has a
set of powerful algorithms, useful iterators,
and is type-safe and const-correct. Old Tools.h++
doesn't and isn't.
Newer Tools.h++ classes are compatible with
the STL, but I can see little reason to use
them beyond backward compatibility. RW does
provide hash tables, but you can get an STL-compatible hash table for free.
Call the wrong function name in java or python and you get a runtime exception; call the wrong function in C++ you get a compile-time error. The difference in these two methodologies translates to raw execution speed. RTTI is underutilized in C++ because it's largely unnecessary and facilitates breaking the strong-data-type model. This model is what makes C and C++ so fast; it provides immediate function linkage with no time-consuming function lookup or indirection.
As with all languages- show me the code -- the final assembly code. I am very impressed with how well templated code is inlined, optimized, and scheduled on multiple-pipeline processors. After stripping the symbols from the executable, I don't detect any appreciable code bloat inconsistent with the increase in speed I received by inlining my collection classes. Even MSVC6 can do this.
With the exception of C (and possibly ObjC), all the languages listed use runtime function-name/prototype to function-code binding which is nowhere near as efficient as C or C++'s compile-time function linking. Your mention of C is either erroneous, or you are referring simply to collection classes of opaque data. This is hardly an improvement over the existing options- particularly since it completely circumvents the strong-type model already available with C and C++.
This is a serious stretch of the truth. Every template you instantiate will increase the size of the code- by the size of the vector constructor code- which is usually a dozen or so bytes at most. Only the functions actually used are included in the code- not every function in the template. Most functions are inlined so you can fully expect those to increase the size of the code while providing an increase in execution speed. The typical functions like begin, end, and iterator increment while typically resolve to a single assembly instruction- less than the equivalent function call to a general collection class!
If you create a vector<string> and a vector<int> you will get two completely different sets of code. The vector<int> will not attempt to call constructors for your int's and can ultimately use an assembly-level memcpy to transfer the contents. The vector<string> will call the constructor and/or copy-constructor of every string you add, which is fine since that's what you want. Two completely different implementations for two completely different types- both optimized for their respective characteristics. No runtime vector implementation is going to provide that, period. You will always get worst-case implementation for both int's and string's because strings necessitate special handling for construction, copying, and deconstruction. At runtime, you get the same poor performance for your int's that you do for your strings.
As for mixing strings and int's in a vector... why? Performance considerations must be weighed against implementation. If mixing int's with strings substantially increases the cost of using the vector, there had better be a really good reason. The first reason might be that execution time is less critical than coding time, in which case, you're probably not using the correct language anyway. Java or python might be more appropriate. Again, use the right tool for the job. As far as I'm concerned, mixing types as you described is a recipe for distaster as it substantially increases the complexity of auditing the code in the future. If I'm enumerating this vector, how can I guarantee that I'm not going to find some other data type in there? Do I throw an exception or try to convert to an int? Or should I convert to a string instead?
It's being used, standard or no standard, because the utility of the language exceeds the cost of failing to compile properly on all target platforms. Implementations which fail to compile properly can be remedied, as necessary, on the build target. Field fixes are common in cross-compilation, nothing to see here, move along.
I couldn't care less if someone derives from an STL container or not. The risks are clearly stated, possibly even overrated. I've found that inheriting directly from a container without declaring the new class as a template itself usually leads to confusion later. A private member variable tends to be more effective. Once you leave the realm of "general template" and enter the realm of "implementation", it makes sense to hide the collection class. Who knows, you may decide to dump the STL class for another class later. If the code which relies on your class breaks when this happens, you've done a poor job at object-oriented programming. Plus, this solves the multiple inheritance problem mentioned by another poster since your new aggregating object can have any baseclass it wants.
Assuming you are compiling with gcc, which covers a considerable number of platforms, just how less portable are you realistically going to be? MSVC does a fair job- ATL COM is built entirely on templates (for better or worse, although their primary objective was reduced code size for ActiveX components- templates where largely responsible for this).
I was a skeptic of templates for a long time until I examined the compilation process at an assembly-language level. Sold! Now I use them daily. The time savings is simply beyond belief. I'll never implement a red-black binary tree again. What a template does for general programming is nothing short of exciting- try looking at difference between the assembly generated by vector<string> and vector<int> sometime- it's inspirational!
-Hope
for all the above cases add
{open angle} new_type {close angle}
between the cast and the parenthisized expression. Those things look like browser tags and get eaten...
so
const_cast <new_type>(existing_object)
static_cast <new_type>(existing_object)
reinterpret_cast <new_type>(existing_object)
dynamic_cast <new_type>(existing_object)
Sorry about that... 8-)
Innocent people shouldn't be forced to pay for inferior software development.
--"Code Complete" Microsoft Press
Just for the non C++ programmers, here's a (real) example of those STL template errors.
This is superficially complicated. All you really need to look at is
conversion from _List_iterator
which tells you you probably haven't dereferenced an iterator before trying to use it or something similiar.
:wq
Check out the Common Lisp Macro System, which is deeply explored in Paul Graham's free downloadable book On Lisp.
On Lisp is a deep, wonderful, mind-expanding book, originally published by Prentice Hall. It's earned five stars on Amazon. The book is out of print, but fortunately thanks to Paul Graham and Alan Apt of Prentice Hall, you can now download On Lisp for free !
-Don
====
On Lisp
Synopsis: Written by a Lisp expert, this is the most comprehensive tutorial on the advanced features of Lisp for experienced programmers. It shows how to program in the bottom-up style that is ideal for Lisp programming, and includes a unique, practical collection of Lisp programming techniques that shows how to take advantage of the language's design for highly efficient programming in a wide variety of (non-AI) applications.
KEY TOPICS: Contains comprehensive presentations of key Lisp features: functions, macros, symbols and interning, variables, scope and lexical closures; object-oriented programming, data structures, and Lisp style. For experienced Lisp programmers.
TOC:
1. The Extensible Language.
2. Functions.
3. Functional Programming.
4. Utility Functions.
5. Returning Functions.
6. Functions as Representation.
7. Macros.
8. When to Use Macros.
9. Variable Capture.
10. Other Macro Pitfalls.
11. Classic Macros.
12. Generalized Variables.
13. Computation at Compile-Time.
14. Anaphoric Macros.
15. Macros Returning Functions.
16. Macro-Defining Macros.
17. Read Macros.
18. Destructuring.
19. A Query Compiler.
20. Continuations.
21. Multiple Processes.
22. Nondeterminism.
23. Parsing with ATNs.
24. Prolog.
25. Object-Oriented Lisp.
Appendix: Packages.
Notes.
Index.
From The Publisher: Starting in the 1980s, Lisp began to be used in several large systems, including Emacs, Autocad, and Interleaf. On Lisp explains the reasons behind Lisp's growing popularity as a mainstream programming language. On Lisp is a comprehensive study of advanced Lisp techniques, with bottom-up programming as the unifying theme. It gives the first complete description of macros and macro applications. The book also covers important subjects related to bottom-up programming, including functional programming, rapid prototyping, interactive development, and embedded languages. The final chapter takes a deeper look at object-oriented programming than previous Lisp books, showing the step-by-step construction of a working model of the Common Lisp Object System (CLOS). As well as an indispensable reference, On Lisp is a source of software. Its examples form a library of functions and macros that readers will be able to use in their own Lisp programs.
====
Take a look and feel free: http://www.PieMenu.com
BTW: Using to bring methods into the scope of a derived class is depriecated.
The new syntax is to simply to declare the operation signature.
Old Style:
class MyClass : private A {
using void method_from_A();
};
New Style:
class MyClass : private A {
void method_from_A();
};
int func(int a);
func((b += 3, b));
Deriving from string is perfectly valid, although it's better to derive from basic_string which is what a string is anyway...
It is absolutely not valid! The string (and basic_string) class does not have a virtual destructor. If your new class is deleted via a pointer to the base class, undefined behavior will result. That is right, the behavior is undefined (although usually your subclasses destructor is just not called).
Very, very bad thing.
Why is it bad to have a function that takes a string???
Better than having undefined behavior IMVHO.
int func(int a);
func((b += 3, b));
> My idea of the perfect standard library isn't one
> that has specialized functions for everything
> under the sun - that is just bloat.
Silly goose. It's not bloat if you don't link it.
It's more tools. Having the right tool for the
job is *always* good.
-I like my women like I like my tea: green-
The only issues I recall being raised had to do with all implementations of the STL not being equally available for all platforms. That may have changed, but from what I recall the implementation for M$ was not quite the same as the implementation on several Unix platforms and that caused some real headaches.
But your mileage may vary.....
ah, business functionality.
That's the point. "Programming" is more than just string comparison and arithmatic.
So, what's the problem with the STL string?
---- It puts the lotion on its skin or else it gets the hose again. It does this whenever it's told.
Now, you are backing that up by saying that the "string" class is slow. That is not the same thing.
Algorithms include things like: sort, find, find_if, partial_sort, count, next_permutation... "string" is not an algorithm.
T
---- It puts the lotion on its skin or else it gets the hose again. It does this whenever it's told.
String in itself has more functionality than most people need. Most of the STL containers do for that matter. Part of the advantage to the STL is that as templates, only the parts you actually use are compiled into the program. If your derivation is in turn a template class as well, you retain this advantage. And even if your derived class is a specific type instance, the linker will remove uneeded code. If you argument applies not to code generation, but just the amount of functionality in the class, your complaint could just as easily be leveled against the whole of STL.
As a good example, suppose your are migrating away from a custom string class, or something like MFC's CString. You can derive from std::string, and then implement compatibility functions as needed, expressing them in terms of the native std::string. This is an excellent first step in migrating away from even the usage of the non-standard functions, since you can now do that incrementally.
Your example of list vs. vector is specious, because where functionality between the two overlaps, there are vastly different requirements in behaviour concerning speed of operations. If that is the case, then yes, you're better off implemnting a new class (or deriving from or containing an instance of the correct STL class).
I grant you that the need for derivation is rare, and most places where it would be used could be as easily accomplished with generic functions that operate on your data structure instead of being a member of your derived class, but there are times when it is more effective to derive. Brad
Jherico
What can the average user can do to ensure his security? "Nothing, you're screwed"
I've heard it said Perl is like Duct Tape, mighty useful to stick a lot of stuff together fairly quickly. However, you don't use Duct Tape to build a suspension bridge.
:)
Perl is a powerful tool, but (wince) with great power comes great responsibility, and that really isn't enforced much in Perl. Perl is one of those languages where a function pretty much depends on the programmer doing the right thing.
In C++, you give someone the keys to your house but you check to see who it is coming in and don't let him in if it isn't the right guy or a close relative. In Perl, you sort of assume the guy wandering around inside your house was meant to be there.
Now, can you write good Perl code? Sure. Good Perl code is approximately as readable and maintainable as good code in other languages. You can write Good Perl code probably as easily as writing Good Java or a bit easier than Good C++.
On the other hand, you can write BAD Perl code pretty easily, more easily even than Bad Java or Bad C++ and Bad Perl is attrocious to maintain or understand.
Perl (even with a graft for a bit of an object model) is a language for hackers - and by that I mean people who don't like to be constrained. It's a language that encourages you to dig into your toolbox, pull out a tool, and have at it. Perl reminds me of the old adage that in times of stress, all tools are a hammer.
But if you want something to run with some stability for large scale deployments of mission critical systems, Perl would be a rather insane choice. It has been done, it has also graphically failed several times in the telecoms world that I'm aware of. And where did the people end up? C/C++. Why? Stability, robustness, etc. and speed.
Perl has its place in the programming Pantheon, but anyone trying to build skyscrapers or suspension bridges with it (or their programmatic equivalents) scares me....
-- Mal: "Well they tell you: never hit a man with a closed fist. But it is, on occasion, hilarious."
A general emphasis of performance over safety pervades the C++ STL and thus programmers must be sure in their knowledge of templates, functors (overloaded function () operators), and the precedence of the various operators. For example if one wants to call the erase() function in a collection class it is important to remember that the iterator should be post incremented when it is passed to the erase function since the designers of STL gave erase() no return value. This is just one example of the types of trade-offs that the STL makes in order to provide optimal speed. If the erase function returned the next valid iterator then this type of kludgy workaround could have been avoided. It all depends upon how erase is used in your program but most of the time one wants to move the iterator to the next valid position after the erase() function deletes the element pointed to by the iterator. The following code example illustrates this behavior (deletes all elements from the map):
typedef map map;
typedef map::iterator map_itr;
map m_example;
.
.
.
for(map_itr itr = m_example.begin(); itr != m_example.end(); )
{
m_example.erase(itr++);
}
I get these warnings all the time from VC++ but it seems they can be ignored. The programs link and run fine. I guess you can't use the symbols in the debugger, but I doubt that the 512-character symbol is really that useful in debugging anyway.
No, you're not talking anally, it's a good question.Try Ada-95, or one of its proper subsets if you want embedded systems.
Rather than give lots of religious arguments, unverified opinions and hot air, here's some resources and quotes:
From Crosstalk (March 2002) :
Parenthetically, I get a little miffed when I see so much unsupported balderdash being purveyed in Ye Greatte Language Warres. Try looking at the experiments people, you know, data, numbers etc? The Scientific method? But I digress, back to the stuff useful to you.
Another Crosstalk article, proving fairly conclusively that a working Ada programs's easier to write than a working C program, at least in some problem domains (high performance, real-time).
Ada for C and C++ programmers shows you how to do what you want, if you know C.
The LRM - Language Reference Manual, ISO-8652 (yes, it's an ISO standard). This version is the one with annotations.
Oh yes, there's an open-source compiler, GNAT available for free download. Like GCC, it's industrial-strength.
Finally, I'll echo my own experiences with the C++ STL: namely, that implementations differ markedly, portability is not a possibility, and performing surgery deep in their bowels is like unravelling rancid spaghetti. But YMMV I guess. Code Warrior 7 and MVC++5 were not compatible for anything other than trivial examples.
Zoe Brain - Rocket Scientist
Obviously, telling you to grovel through someone else's template declarations isn't a particularily strong argument in favor of the STL, but it might solve your problem.
John
However, in practice, most of it indeed works as advertised. You shouldn't have much problem.
This first statement is literally true. But the second statement doesn't always follow, and just one exception can be a major roadblock to development. In one case, an STL hashmap acquired sporadic memory loss somewhere around 700,000 entries. Identifying the cause of this application malfunction swallowed large amounts of QA and developer time, and made our department responsible for pushing back a release date. With extensive testing, if you have the time for such testing, the STL can be a good tool. But in retrospect, whipping up our own quick hashed map would have been the stitch in time.
Actually, STLport is almost close to a standard implementation. It's extremely complient, high-quality, and free so you can use it wherever you need to.
A deep unwavering belief is a sure sign you're missing something...
i've used STL and i love and have hated it. you do it right, and walla, all kinds of jizzy things are easy. OR make some teeny mistake and you get 5 lines of extremely dense and unhelpful error messages.
.NET components, C# and/or "managed C++."
I've found that the STL learning curve is steep at the outset. BUT if you've got some teammates who can help you along, good: get a copy of the Effective STL books and _Modern C++ Design_, and take a peek at the boost library.
Once i started reading _Modern C++ Design_ and I started grokking "generic programming" better, funky games with templates, and the mindset of library designers, i mean GOOD library designers, woah! suddenly i got to understand *why* i'd see those 5 lines of unhelpful error/warning messages.
When i taught C/C++, one of the least PC things I say is that the compiler issuing error/warning messages is like a girl saying "no when she means yes." The compiler will say one thing when it means another thing. Thus the ugly error messages. The coolest things in boost/loki/STL are done in spite of the language/compiler, thus when you get off track, you'll see goofball error messages because of those workarounds.
Recently, we had a program that was running slowly. But a key data structure doing a linear search of a big array was done in STL. We changed 5 lines and suddenly a different more efficient search algorithm went in and walla, we saw a big speedup. if we had NOT used STL, we would have gone 'oh shoot, we picked the wrong data structure.' Just changing a vector to a multimap did all that.
Flush from this success, we tackled another problem that was jsut perfectly solved by a functor object. Heck, i couldn't even spell functor 6 months ago, and i've been hacking C/C++ since 1984 and I think that getting into STL has opened up a whole new set of paradigms that every C/C++ programmer should have.
In the old C days, i was a total weasel with the preprocessor, and that became wicked under C++. With templates, generic programming, and all those STL paradigms, you're exercizing the C-front parts of the C++ compiler, which may explain why I like STL weaselology.
If you're unwilling to learn STL and climb that learning curve, pick up VB and wrastle with getting the right VBX/OCX components installed, OR sell your soul to the Dark Lord and use
Or you could do Java. but i don't know how to do "generic programming" in Java.
There's some stuff that didn't make it into the ANSI C++ standard that probably should have. Stuff like reference-counted smart pointers makes doing things a lot easier sometimes, especially once you start throwing pointers around inside STL containers. The stuff is quasi-standard; many of the driving people behind boost.org were members of the ANSI committee itself. Definitely worth a look.
www.boost.org
You're right, I was assuming that you were using a specific meaning for the word that matched mine. I should have referred to source code, or something of the like. Nonetheless, I stand by my points, with the correction that where I say code, I should say source code.
For those of you complaining about the huge error messages that the STL can sometimes cause, you might want to try this:
http://www.bdsoft.com/tools/stlfilt.html
I haven't tried it because I haven't done anything with the STL in a while, but it seems pretty nifty. It's basically a Perl script that you can use to decipher the error messages into something useful. There's even instructions on how to make it work with VC++.
This article has a better description and an example, in which a 20-line error message is reduced to plain English.
(* This is due to template expansion, especially with STL classes (most of them) that take a large number of arguments, most of which have default values already. *)
Sounds like you need named parameters, so that you only have to supply/mention those that are different than the "norm".
Is there any plan to add them (real or template-based) to the standad? I have been out of touch, so they already might be there.
Table-ized A.I.
Sure, you can do this. But do you really want to leave the type system even for a list of bananas or apples?
Uh, that was my point. If I wanted to cast to void *, I'd be casting to void *; I am not prevented from doing this in C++. Java just enforces it, albiet via a lack of templates.
Daniel
Hurry up and jump on the individualist bandwagon!
STL implementations use some of the most obscure features standardized in C++, often triggering behavior in the compiler that may or may not conform to the standard exactly (do you understand the correct semantics for partial template specializations?). Or sometimes bad code generation.
Debugging isn't too easy either.
That said, I do use the STL in many programs because it provides things I need (strings and containers, mostly).
I'm working on a group project in C++ for school, I usualy code in java. Anyway, I made one simple mistake (I think using the
10 compiler errors for one typo!
autopr0n is like, down and stuff.
You're correct... That's what I get for remembering that there is a way to do that with templates...
Here is the code that actually does what I was aiming for.
It's been a while since I've done anything with templates... the joys of being in a CS department that worships at the holy altar of Joy and Gosling...
with the class documentation open in a web browser at all times since it's so hard to remember the inconsistent naming
You really ought to get a decent IDE. A couple of reasonably good, free ones are AnyJ (http://netcomputing.de/), which is free as in beer for Linux but pay-for for Windows, and NetBeans (http://netbeans.org), which is free as in beer and speech (SPL, not GPL). (Standard disclaimer: I have nothing to do with either group or IDE, other products exist, etc)
I'm assuming that you use a text editor for coding; trust me, once you've used an IDE with built in compilation and debug support, and a CodeInsight-like feature (which suggests possible completions for what you are typing, either automatically or on demand - no more having to have the docs open to remember what methods a class has!), you won't want to go back.
The only downside is that, being pure-Java apps, you're going to have to have a reasonably beefy machine. JBuilder (commercial, expensive, what we use at work) performs adequately on a P3 450 with 384MB of RAM, most of the time.
It's official. Most of you are morons.
... how nasty pointer errors can be in C. I wrote that purely off the top of my head, and didn't ever bother to think that the return x < y should be return *x < *y instead.
Simple error to make; anyone who's written more than 100 lines of C has likely done the exact same thing, more often than they'd care to remember.
On the other hand, the C++ code works just fine, and exactly as intended.
If you chose to use C++ for its object-oriented abilities, you may be surprised to know that Alexander Stepanov (the inventor of STL) himself said he never uses what he calls "inheritance, virtuals - OO gook" of C++, and says, "I think that object orientedness is almost as much of a hoax as Artificial Intelligence. I have yet to see an interesting piece of code that comes from these OO people."
This may or may not be of any importance in your choice of language features and development practices.
There is no ISO98 C++ hashmap. What you were using was a vendor extension. As such it probably wasn't put through the same rigourous analysis that every standard container has.
But yes, that sucks. As is the case most of the time, the last 90% of the time.
- I don't need to go outside, my CRT tan'll do me just fine.
Some aspects of the STL can be overly constraining. I find it very unnatural to have to specify one and only one comparison operation that dictates the sort order of a vector. In C, if you want to sort things differently, you can hand a new function pointer to qsort(), but with the STL, you're kind of out of luck. How would you go about writing a (thread safe) program that allows the user to sort something according to run-time criteria?
vector doesn't have a sort order, as it's not a sorted container, you can sort them at runtime with sort() or one of the other sorting algorithms.
Containers like set need a sort order specified because they are kept an a sorted state all the time.
--
Benjamin Coates
It's bad to have a global function when you should be writing OO. The string object should know how to do a format operation on itself.
The subclass needs no destructor anyway, since it's just extending the methods of a predefined class, not adding destructable properties to it.
btw. The whole virtual destructor thing is a red herring. Unless your compiler is seriously broken it'll work fine (it certainly does in VC++) - each object knows what type it is & knows how to destroy itself.
The C++ kitchen sink approach to OO just plain sucks, but I find the newfangled generative stuff intriguing. Back in school we tended to settle on a more manageable subset of C++ functionality. You really don't have to use every obscure feature and than it becomes better. You can also write perfectly fine object code in plain C, using structs and function pointers. In fact, the most beautiful OO design I've seen in a real program is that of the Freetype library, written in C. For embedded folks, C++ is usually a non-option. On many small platforms, you'd be happy if your C compiler is working as advertised.
I don't follow the problem you have with compiler flags. Even if you compile parts of your code with different flags, you can surely still link them together?
Seriously, dude, take some time to actually learn all the cases, rather than just blindly quoting some overly-simplified rule that you read in some style guide.
It's not being overly dramatic, this is coming from spending more than one late night debugging code because some entry level person who doesn't know what their doing didn't make their base classes destructor virtual.
There's a lot of things I can do safely but would never even consider doing in a production environment because while *I* may know what not to do, I cannot guarentee that others will.
int func(int a);
func((b += 3, b));
That must be the San Francisco-based subsidiary of Rogue Wave, right?
In 2001, Bjarne Stroustrup started a dialogue about the future of C++. As primary inventor of C++, Bjarne is giving interviews, visiting user's groups, and posting in forums, all with the intent of stimulating discussion about where C++ should "go." It's an important topic for software engineers, and everyone has a laundry list of features they'd like to see added in the next revision of C++.
I'll buck the laundry-list trend and suggest some things I don't want to put in the next C++.
In my experience, C++ iterators, algorithms, and containers are inefficient and unnecessarily complex. The actual source code doesn't look terribly confusing — it's the underlying mechanisms that obscure function with too much form. We heap template upon template, giving the compiler nightmares while obscuring what is really happening "under the hood."
Is container abstraction akin to the hiding a car's pistons from its driver? No, because I'm not driving the car, I'm building it. And as any good engineer can tell you, hidden complexity and obfuscated parts have been the bane of many software (and hardware) projects. I have no problem with containers being part of the language — what bothers me is that the current set of containers is complicated and inconsistent. We need to refine the current standard before we begin adding new material; otherwise, we build new code on uncertain foundations.
An official template library also leads to another question: Just what is a "standard" container? Some people argue that, for the sake of completeness, we should add hash-based containers to the standard library. But "completeness" means different things to different people; someone might want balanced binary tree containers, while others would prefer B-Tree or r-tree implementations. And then we get into the whole issue of graphical development — and you end up with Java, that tries to be everything to everyone but does few things particularly well.
The current template library is much too heavy, prone to the "feature creep" inherent in a committee-based standards process. And when the standard includes an inconsistency, (list<>.sort() comes to mind), we're stuck with it. Should a list be sorted via its member method or the sort algorithm? And what constitutes a "required" container feature? I use about 20% of the vector<> template 80% of the time; it seems to me that C++ needs a functional hierarchy that stems from a set of concise "base" containers.
We also have the entire realm of garbage collection and "smart" pointers, which is a nasty tangle of divergent opinions. The auto_ptr<> type has numerous logical and practical problems, as does the Boost smart_ptr<>. I don't believe one type of smart pointer makes sense for all applications — and C++'s experience with auto_ptr<> should teach us to avoid providing specific solutions to general problems. I'm still not convinced that automatic garbage collection is a good idea in most applications; it tends to make programmers lazy about controlling their resources.
I've always preached that code should be no more complicated than necessary — and that includes the code I obtain from language libraries. The C++ container types are heavy and detailed, when what we need is a simple set of light, fast containers, with hooks for adding algorithms that fit individual application needs.
Anything else is trying to be Java. ;)
All about me
Actually, RogueWave's documentation was inconsistent with their own implementation, at least last time I checked.
The case that brought it to my attention was the map delete. There was supposed to be a version that returns an iterator to the position after the location you're deleting; however, while the documentation for RogueWave said it DID, the signature had a void return type (both in the code and in the signature within the documentation itself).
I'm not saying things haven't changed since then; they may well have. But at the time, that was a dead-end and obviously erroneous documentation.
Xentax
You shouldn't verb words.
so what are the downsides to the STL?
My pet hate is that Templates subvert Polymorphism and so cause excessive code bloat.
Since each new templated type added to the project generates an entirely new class, the size of code base can rise exponentionally.
Unfortunately there is no easy solution to this problem. A Hand-crafting solution whilst producing much smaller code also requires a lot more work, and requires good OO design skills. STL magnifies the easy of use vs utility trade off.
Perl 6 has not been written, and the attempt of one contributor to code a C++ prototype has, as far as I can tell, been abandoned. Check your facts.
He is a bit of a formalist, and from a formal point of view (for formal reasoning such a correctness proofs), OO is a disaster. You can reason about the state after a call to a virtual function.
OO is damned practical though, mostly because it is so easy to design for. Classes and methods can directly reflect entities in the user sphere. Which is why C++ is such a lovely language, you can use OO for the application area oriented part of the design, and generic programming (stl)as a lower level toolbox for the computer science oriented part of the program (containers and algoritms) which should not concern the user.
In one-paradigm language, the design will often either be too far away from the user, or too far away from the computer.
This is simply nonsense. Java does not enforce it. It is even not allowed in Java because Java has a safe type system unlike C++.
Object is functionally equivalent to void *, with a little runtime type checking added. Your program still crashes if you misuse it, just slightly more pleasantly. (is there such a thing as a pleasant crash?) Heck, if all the classes you're using are your own, you can add your own primitive base class in C++ and use dynamic_cast.
Anyway, the point is, Java has no containers that preserve compile-time type-checking, the last I heard (although someone is supposedly working on templates), since any generic container forces you to cast to Object and back.
This is not necessarily a bad thing -- some languages have no compile-time type-checking at all. However, when the language supports static type-checking most of the time, it seems a real shame to lose it just so you can use a generic container. That's why I don't like casting to Object or void * even when I have to.
Daniel
As an aside, and to get back to the root of the thread, I think it would be *nice* if C++ had a primitive base class; I just disagree with the claim that C++ *forces* you to use templates for generic programming by not providing alternatives.
Hurry up and jump on the individualist bandwagon!
My word choices in my argument weren't perfect, what I meant to say is that you shouldn't add more functionality than everyone using the class will need. Since everyone using STL is huge, the only consideration the STL designers need to make is if enough people will use it and the operations are integral enough to the class that the added confusion the extra methods add to those who do not need them is offset. I admit that vector vs. list is contrived, but I think my argument stands regarding polymorphism vs mental models.
I understand the convenience of the decorator design pattern over aggregation and extension, but the decorator is there for when you need to plug new functionality in situ polymorphically, which is generally not the case for a utility class like basic_string (the class operates only on memory data and copying and conversion are reasonable alternatives.) Your examples seem to indicate your class doesn't need to have a is-a relationship to basic_string, it only needs the functionality of basic_string, so is-a becomes a source of confusion (and possibly defects if users of your class take advantage of that relationship by casting and therefore possibly failing to call your non-virtual destructor) to other users and only saves you a couple of hours of pounding on the keyboard to write wrapper methods for your new class that delegate to a contained basic_string instance.
personal attacks hurt, especially when deserved
The answer to this one is simple-- never trust a vendor who forces you to instantiate templates a certain way. Especially one that forces you to use -frepo (oh, and never use -frepo ... )
qsort uses the quick sort algorithm, C++ sort uses merge sort, which has better worst case perfomance. And the compare() function in C should return the difference, not a boolean, but I don't know how that will affect the outcome.
The STL is great overall, but the generic algorithms (a.k.a. algorithm objects, functors, whatever else you want to call them) are clumsy. Methinks this is due to string typing & lack of anonymoous classes.
Generic algorithms in STL aren't as useful (yet) as their equivalents in Java, Smalltalk, & Lisp (& probably a bunch of other languages).
Overall, the STL is a great timesaver when programming in C++.
gene
Yeah, I corrected myself a little further down :) Stupid HTML...
:)
Preview, what's that for
int func(int a);
func((b += 3, b));
I looked at the hawkstein/lkaos debate
/. discussion :)
That's a cleaver way of referring to a
I haven't read Modern C++ Design, and I will probably take you up on your advice, but I would at least like to point out that the "debate" ended in the realization that his example could be implemented easier and more efficently *without* using inherentence (sp.).
I still stand by my point that there is no good reason to inherent from an STL container (although there is one justifiable reason that I had to conceed to in another thread...).
That is because C++ does not support template typedefs so using inherentence to simulate template typedef'ing is excusable.
I actually agree with your explanation of generic programming and I'm curious to see what you thought my view on it was as our conservation regardded inherentence, not generic programming (unless we had another thread going to somewhere).
int func(int a);
func((b += 3, b));
cough*kyoto*cough!
I know this thread should really be dead, but I have to respond. I'm not confused at all. I know in great detail what I'm talking about. Here's the scoop:
Hash tables have *amortized* constant time lookup, but worst case behaviour is linear. There are two basic approaches to hash table construction, and they degrade in slightly different ways.
Open coded hash tables use (something like) a vector of cells indexed by the hash value. If there is a collision, you rehash (compute a new and different hash) or scan for an open cell and use that. In either case, you keep going till you find something. This leads to linear scan on a nearly full table. Maintaining these requires the rehashing process you describe.
Bucket hash tables used a list in each cell. You hash to the cell, then scan the list. In this case, an over-full hash-table has long lists to scan. Again, linear in the worst case.
In both cases, we're assuming a good hash function. One easy way to get poor performance out of a hash table is to have a poorly performing hash function.
Now, with respect to the STL, the issue for the designers was, in fact, worst case performance; not expected case performance. Call it a design guideline if you will, but that is what they used as a criterion.
So, as I said in my earlier post, Hash tables were not in the standard because they have poor *WORST CASE* performance. Never-the-less, the good folks at SGI have produced several high-quality hash table implementations that are STL compatable (so have I, for that matter). At some future time, I expect that those hash tables will be added to the STL because they are quite useful, when used properly.
There are several good works on the topic. Knuth's "Art..." being the seminal work on complexity. He covers both types of hash tables in detail in volume 3. I also recall a paper by Stepanov discussing both the ideas behind the STL and the tradeoffs. It's fairly old -- circa 1990 or so IIRC.