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?"
This may really only be a major concern for embedded and realtime platforms, but there is a lot of overhead with using the STL. Virtual functions and things of that like can make your code bigger and slower. The impact may not be noticed on a desktop system, but can cause havoc on your real-time requirements if you're not aware of them.
Use your own functions. Remember linus, real men code all from the ground up.
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."
The STL uses templates, not an object hierarchy. And code that's heavily optimized for speed. Everything I've read has said that performance isn't an issue.
First post? I dunno. Anyway, one of the bad things about the standard library is spotty compiler support, especially around the edges where you can have goofy things like template template arguments and so on. Still, when it works, and it works most of the time, it can be a real treat to program it. I'm becoming a big fan of it myself. Meyer's "Effective STL" is a great book about the gotchas that lurk inside the STL (there be dragons :) ). I would have loved to have gone to a session by Meyers...
disadvantages:
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.
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.
I encourage you to encourage her to get a strap-on dildo. It's absolutely fabulous to get fucked in the ass by your girlfriend. Just take your time to get used to the dildo up your ass.
Digital Theatres
And there are a few in Canada, most notably:
Famous Players Paramount
259 Richmond St. West
Toronto, Ontario Canada M5V3M6
Tel: 416-368-5600
Go raps!
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.
Extant versions of MS Visual C++ still don't support lots of important aspects of templates. You usually don't get bitten until you're writing your own STL-style utilities (ie just using the stuff is fairly portable). Someday MS may get their act together and make an attempt towards ISO compliance.
... it isn't Java
*rimshot*
uh... wait,... that wasn't a rimshot... that was the sound of downmoderation... *grumble*
Good quote, too many chars. Seriously, the slashdot 120 char limit sucks!
It's a template based library, so it has all the problems associated with templates:
Long compilations on most compilers, but worse is horrible error messages when you make small mistakes. Every type is a template with two or more arguementsIt happens because every type is actually a template so you get very long error messages.
But it is still a great library, very efficient and highly expressive.
Use the mirror!
In what ways are MFCs superior to STLs ? Pray do explain the benefits to us all... Is it just me or are MFCs 'good' for windows centric exclusively?
And hopefully you used condoms as well.
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.
I used to use RW for server side stuff -- switching to STL along is a poor substitute. The string class is much poorer and the msdev STL implementation is nowhere near as good as RW. OTOH, Rogue Wave is pretty expensive (which is why most people switch away from it I imagine...)
Good luck though!
I am not a number! I am a man! And don't you
Alot of overhead and tons of memory leaks. STL has not been tested as well as one might think...
except of course that the MFC makes your executables the LARGEST things in the known universe. MFC is good for GUI app programming bad for everything else. It includes tons of libraries into the .exe and unless you are doing GUI you won't use most of them.
Doesn't that stand for Sexually Transmitted Disease?
Also M$'s implementations of the STL are buggy and broken despite these problems being noted since release 1.0.
M$ dislikes ALL standards they didn't create?
Dunno....
My limited experience with STL was pretty satisfactory, but I had a lot of trouble finding either a well-written reference or guide. There are plenty of books out there, but I had to study them pretty seriously and do a lot of learning-curve testing before I felt comfortable using the library.
Otherwise, the STL design is pretty rational. I'll continue using it.
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.
I find that much code I want to write requires database-like functions like join. I dont mean that it requires any of this necessairly written to disk. STL has all sorts of ways of indexing to speed up searches and inserts and do it cleanly. But then it misses the next key step which is join.
Once you've got used to it, the STL is a great productivity booster. No more writing those generic data structures. I'd say anyone using C++ who doesn't know the STL is missing out on a large chunk of useful knowledge. Unfortunately it takes a long time to master it (I haven't reached that stage yet!).
Problems? I find that executables can become quite large if you use the templates all the time, without thinking how large the code for all these classes can be. You have to think about using vector<T*> rather than vector<T> (vector<T*> is specialised).
Another problem can be the warnings from compilers. gcc-2.95 has awful warnings for errors in using templates. It's good to have a modern compiler (e.g. gcc-3.1), which doesn't leave you with an awful mess of < < blah > blah >. This is a general problem with C++'s template syntax, which can become very messy! I'd love a language which really cleaned up C++'s syntax generally.
As far as I can tell, STL is supposed to be standardized, but there are different implementations out there. You must always be wary when migrating your code. Different compilers will implement the STL, well, differently. This basically means that you'll always have to debug and test your code on every OS and with every compiler.
Another drawback is that STL methods don't parallelize that well.
Those who can, do. Those who can't, simulate.
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.
Here's my only beef with the STL: memory management. I've run into many situations where the STL memory manager just won't seem to release memory, especially in the string class. Now, it could have been the specific implementation that I was using, but I've seen many others with the same issue.
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
Well obviously c++ is not c so it is not the One True Language and there for totally sucks ass and is just trash. C is The One True language and any innovative open source hacker knows c is the greatest and should be used for the rest of eternity and if you disagree i will declare a fatwah on you.
please not the sarcasm. thanks.
Extensive use of templates can result in substantial executable code expansion. If you know what you're doing you can mitigate this by sharing code between instantiations. Like other time/space tradeoffs in C++ it requires the exercise of programmer judgement.
Template code can be the most obscure, insanely ugly code imaginable.
So much so that I believe it's not worth it for most of the uses people have in mind. Fact is, if you can't read, you can't fix the bugs, you can't maintain code someone else wrote, etc.
And in my experience there are some really hot-shot C++ gurus who can look at any C++ code and instantly know exactly what it means and whether it's written correctly or has fallen into one of the (many) C++ legalistic potholes. But I don't believe your average C++ programmer falls into this category. As soon as you get beyond the trivial uses for templates you get into code that is inherently prone to error simply because correctly writing it is very difficult, mistakes and mistaken assumptions or understanding become common, etc.
If you don't agree with this assessment, just go look at the STL code yourself. It's template code, so you get to see the sources. Now, if you could actually implement that yourself, then you are one of the gurus I mentioned earlier. If you couldn't, and be honest with yourself, then you are playing with stuff you don't truly understand, and that is a recipe for disaster.
As Brian Kernighan once said, debugging code is inherently twice as hard as writing it, therefore if you are writing code that is as hard as you know how, by definition you are not smart enough to debug it.
This is true for C++, in fact I'd argue it's not even just doubly true, it's triply true.
STL is good, but realise the limitations. STL can only store objects, not pointers, unless you write a class to wrap the pointers (Simlar to a smart pointer class). Therefore to add something to a list a copy is made. Thats why copy constructors are necessary. You do know the difference between a deep and a normal copy ?
They are useful, good knows we don't anyone to write another linked list class, but lots of copying can go on behind the scenes.
Welcome to C++
more mentally
from my expirience
a. Management heard that it is bloated, not readable etc -- you will have HARD TIME to get permission to use it.
b. Not all programmers are equal - if somebody does not understand your code, they will try to make look like all the bugs are came from this particular code. See a. as well.
c. If there is even a slight possibility that this platform is not support some standart feature (old compiler, etc) you better know it in first place so b. will not led to a.
All other things like code bloatness etc -- well, if you write embedded app, you better be carefull. YMMV, you know...
Okay, thanks Bill. Another drone with the M$ blinders on that will never look at another API.
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.
Here's the portable SGI STL library, which is pretty good. Replace the crappy VC++ 6.0 version!
http://www.stlport.org/download.html
My Other Computer Is A Data General Nova III.
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.
Uhhh. Do you know what you are talking about? The container classes in the STL blow the MFC container classes out of the water. I doubt that the engineers at Microsoft would even argue this point (I wonder what Herb would say). Furthermore, MFC simply does not have anything comprable to the STL algorithms. Nothing.
You do realize that the STD, as you call it, is not a GUI library?
Different implementations have different degrees of thread safety. Some implementation are very good with thread safeness, others don't do anything and most fall somewhere in betweeen.
Brett
Template error reporting is, at least in MSVC, almost totally incomprehensible. It takes quite a long time to figure out what each error means (and it's not usually that easy to figure them out.) And, remember to put spaces between your >'s. If you don't, the compiler will mistake them for shift left and right, and the errors don't help.
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.
To me the *concept* behind the STL is good. It's meant to be generic with little speed reduction. I just don't think the C++ STL is a good implementation.
My Reasons:
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.
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.
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.
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)
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.
I fight extremely hard to not use the STL as there are other well-tested non-templated implementations of what the STL has.
These are my problems with the STL. I have other problem with C++ in general but the STL can't be faulted for those (except the STL is in C++).
The STL does have advantages but I don't think the advantages outweigh the disadvantages.
--sea
groten
One problem that I've run into in MS Visual C++ is that the debugger has a different allowed symbol name length than the compiler (512 max for the debugger). The only time this was a problem was with some client code using embedded name spaces and templates containing STL templates (don't ask). The same code could be compiled and debugged under gcc/gdb, and the problem may have been fixed in more recent versions of MSVC++.
As far as the STL itself goes, it can save you a lot of time and trouble, and is becomming available in more places all the time. I
MFC and ATL use STD.
STD brings more than algorithms. They have a good consistency in concepts and paradigms.
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++.
-
The "Standard Object Oriented Library" for C++. You'll find it here. (Warning, blatant goatse.cx link)
What the hell are these specification designers thinking? Just throw everything in there? We make a language (an extension, anyway) with somewhat decently implemented classes and objects. Years later we remember we haven't written a library for it yet. At the same time some brightlight wants to add templates to the already horribly complex language, and so we create our standard library using this new feature and nothing else. The STL isn't just based on templates for rational things like containers, it uses templates for everything imaginable. Who needs a template parameter for an allocator function? Who needs strings to be such a generalized class that I can use them to handle an array of kitchen sinks, and provide automatic Dran-O too? The "joy" of templates drove every other thought out of their heads when they came up with this crap.
Programmers code in different ways. Not everyone wants to use templates; they're by far the most debated "feature" of C++. Why the hell did Stroustroup et al decide to ram them down our throat? When I program in C++, I use standard C libraries or roll my own object-oriented ones.
Just wait till next year, when they add threading support based on functional programming and graphics code which uses an AI core to figure out what you want to draw before you know it yourself.
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.
Im obviously missing something here.How is he switching from "rouge wave" to the STL exactly? Serious question - what product do they produce?
I *think* I've been using the ROGUE wave STL for years - it was purchased by Borland and incorporated into C++ Builder. If you want a good implimentation of the STL thats the product I'd recommend. VC6 STL support stank to high heaven if I recall correctly and I'm not sure how it fairs in the latest version.
Speed isnt an issue with Builder, code bloat could be but there are ways to minimise the impact and the documentaion in relation to the STL is *excellent*.
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 :)
To sum up the different comments - the only real downside is the implementations on the different platforms. First of all, not all compilers have STL implemented fully (I think g++ 3.1pre has it all). Second, older systems and embedded systems totally lack an STL implementation. The rumours about the STL having a lot of overhead because of virtual functions etc. is not true - one of the goals with the STL was speed and therefor it was implemented without virtual functions, but just concrete templated classes. Sure, a std::vector has overhead compared to a built-in array, but development is usually faster using vector because it dynamically resizes and it throws exceptions when trying to reach an element which is out of range.
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.
One of the problems with using templates in interfaces is that STL implementations may not be binary compatible between releases. Imagine the following libary interface:
mylib.h
-------
vector<blah> getBlahs(void);
The vector<blah> implementation is compiled into both mylib and the application that uses it (mayapp). The nasty part is that if mylib and myapp are compiled with different STL versions, then they may not be binary compatible. I encountered this problem when moving to gcc 3.0. It was amazingly difficult to debug the problem.
Also, the gcc and VC6.0 STL implementations suck and have subtle incompatibilities.
So, after being bitten hard a few times, I try to avoid STL like the plague.
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.
Tales from behind the Lagom Curtain
The error messages from the compiler whenever anything goes wrong.
You know the ones I'm talking about, where the compiler unravels all of the levels of templates, leaving you with an error message that's about 20K long, most of it angle brackets.
They're wonderful tools -- but mind you, like any other tool -- they can cause you great problems when used incorrectly. Watch your portability, and keep your code easily understood. Don't use every odd feature just for the sake of using it. Just be smart in your usage of the STL. I personally use them both in large scale projects, and think they're wonderful.
Bear in mind, you're likely to see lots of negative press in this slashdot story. Remember -- The STL's and C++'s biggest detractors tend to be those who don't understand them.
An alternative is the LEDA
suite of tools. Not only is it a faster implementation of the STL but many useful graph functions are built in. I know its not free, but they give out free licenses to students and anyone working in a research environment.
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?
A number of postings have complained about the fact that many compilers / platforms / libaries do not follow the STL standard precisely. If that is one of your concerns, I suggest using Dinkumware's standard libary. This is the only implementation of the C++ libraries that is truely 100% specification conformant and well documented. I am not affiliated with this company in any way, but their stuff is kick-ass. So if you need something that works across platforms etc., go with them. As far as I remeber, Intel's C++ compiler also supports the dinkumware libararies, and is very ISO C++ compliant. If you use these two together, then you may end up with 100% ISO C++ / STL compatibility / support. Porting applications from one compiler to another or from one library flavor to another can be a bit painful. I would suggest you pay the price of kick-ass commercial implementations and start with them right from the beginning, if you care about these issues.
The downside is, craybob, that "STL" is spelled just the way it sounds, and therefore you can't have the same kind of fun you can have in spelling "Rogue Wave" the same way you spell the name of that red stuff used in cosmetics and lapidary.
(This is, like, the third time in a few days I've seen "rogue" spelled "rouge". Is it something in the water?)
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.
There are a handful of utilities that are designed to "translate" these types of error messages, and produce something human-readable (or at least developer-readable.)
I suspect that compiler writers will eventually start using these same sort of techniques to present usable error messages for STL constructs. Hmm... might actually be interesting to do this for GCC.
"Great men are not always wise: neither do the aged understand judgement." Job 32:9
C++ already, innately, carries with it a certain number of performance hits.
And not all compilers handle templates in the same manner, or even correctly. By their very nature, templates create a lot of bloat. There are, however, tricks to keep that bloat to a minimum though.
As already mentioned by many others here, STL is NOT a standard, but nonetheless, the currently best "implementation" is STLport. They actually strive for complete portability, unlike most implementations. They also strive to make sure it works with other programming features such as multi-threading.
// file: mice.h
#include "frickin_lasers.h"
Stupid HTML
int func(int a);
func((b += 3, b));
You should dump rogue wave. My company has been using tools, threads and thir stl. They have changes their licenceing so that rather than paying about 5k we now pay 50k because we distribute the binaries to customers. We are looking to dump them infavor of standard ms stuff because it will save us a ton.
.sigs suck, thus nothing here.
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)
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.
Trust a slashdot geek not to know. It would just be theoretical knowledge, anyway.
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.
Try Python
It's way easy to learn and understand and extremely powerful. Integrates well with C/C++.
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.
Everyone thinks template compilation errors are tough to look at. True, but looking at STL contents with a debugger makes me want to punch a cat.
My main quip about the STL is how hard it is to debug. Its difficult code to follow. The second quip I have isn't that big really: I always have to have a reference book handy becuse the header files may aswell be encripted! Otherwise I love it! :)
The real problem with the stl, (and C++ in general), is that the knowledge required to use templates is on the same order as the amount of knowledge required to make good use of classes, the C++ library, and the core 'C like' language.
Understanding, and making good us of, all of the C++ feature is significantly higher than C.
core language + library + platform => C
core language + library + objects + templates + stl + platform => C++
1: Build times and object sizes can go up. Way up. Often to unacceptable levels when using compilers that aren't adroit with templates, a la early HP-UX aC++.
2: Many STL classes are difficult to derive from.
3: Syntax can become convoluted when using complex structures, e.g. nested maps.
4: STL containers tend to do a lot of small memory allocations, with concomitant potential performance and fragmentation issues. (Mitigating factor: you can plug in your own allocation code.)
5: There are no virtualized containers (in the Standard, anyway,) which can lead to a lot of memory being expended on data which might be better held in a temp file.
With the exception of [1] these are relatively minor concerns; I use STL daily, and wouldn't willingly do without.
ddb
Life is like surrealism: if you have to have it explained to you, you can't afford it.
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.
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?
I see "Rouge Squadron" is due out this week on the Gamecube in the UK also.
For once I cant just say its thick Americans bastardising their mother tongue *sigh*.
For example:
http://www.dinkumware.com/libdace.html
It's pretty decent although it can get expensive if you need to license it for a large development team.
-- Erv Walter
The most common complaint I hear is that it is too complex and takes too long to learn. I would agree with that if you are only trying to write a simple application, but in that case you could probably get away with just learning vector and string. Who said good has to be associated with easy to learn? (Maybe vim is a good example of this....)
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.
It's cool that we are not the only one leaving Tools.h++. RogueWave did some relly not very nice licencing changes. they though that they had us by the balls and just made a huuuuge adjustment to the license terms. That made us drop Tools.h++ the same day. STLPort is much better!!! Pitty we did not try it to begin with...
I intended to write a smaller essay on this matter, until I realized the one asking the question still thinks of it as STL.
The fact is that since the ISO/ANSI C++ standard was ratified in 1998 there is no "STL". A "C++ implementation" is required to supply, among other things, what used to be known as STL.
As such, the question "so what are the downsides to the STL?" could be summarised:
It's an international standard, and Microsoft can't buy it and destroy it (or as they say, "embrace and extend" and extuinguish).
The downsides are that you write portable code (this is a _real_ downside if you're a Microsoftie since it's the opposite of the corporate policy of "lock-in" and "vendor dependence").
I think your question is malformed. It should have been "What can we gain by using standard C++".
There is no compiler available that can optimize away the bloat the stl generates. Code bloat might not be a problem memory wise, but it'll have an impact on your instruction cache anyway.
Debugging usualy involves rewritting the bit of code without the STL so you can actualy understand the execution path.
If you, by mistake, fall into the STL itself with a debugger, you usualy stay there for the next 10 minutes trying to step out of it.
Usualy teaches non-experienced programmers to write stupid code, like passing objects via value instead of references "because the compiler will optimize it away" Or making a vector for 5 bytes "so I can't go out of bounds because the operator [] checks it for me". Or using hash tables for 10 values maximum "because hashes are fast!", etc etc. makes for lazy bastards you'll have to Zap +4. Oh and they swear recursion is cool, too. Stack space is infinite after all.
char *data;
memcpy(data, someotherdata, somesize);
"Why it crashes, my data is declared!"
Of course, the zealots will tell you the contrary, but heh, I've been mopping behind that kind of 'programmer' all fresh from school and full of STL crap for a few years.
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 c++ stl is great as far as it goes but it doesn't compare to the standard libraries that come with other languages (java for example).
struct tm.tm_isdst
If it's set, it's DST, if not, it's not.
(1) Portability
Portability isn't always great, especially with Visual C++. Plus VC++ gives hundreds of warnings when you use STL classes for no real reason whatsoever ("identifier too large"), making it hard to find real warnings.
(2) Overhead
People that use STL claim that it is fast. This isn't always the case. OLog(n) is great except when O is large. Plus templates tend to expand your code size, which can slow down runtime due to limited cache size. Some commonly used methods, like size(), are much slower than they should be for dubious reasons.
(3) It's really hard to get the syntax right
The syntax of many common things in STL is really weird. Sometimes you create objects containing single methods rather than simply passing methods around, for example. I constantly find myself Googling for examples.
(4) Compiler errors
Compiler errors with STL are horrible to read. It's really hard to figure out what's wrong sometimes.
(5) Read Scott Meyers book
Read the book. If it doesn't scare you off, then you'll do fine with STL. But remember that other programmers might not be as willing to put the time into learning it as you.
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.
One implementation, well documented, threadsafe or not (your choice), consistant support. Yes, you suffer in performance and memory requirement compared to C++, but most software I write has a heavier weighting on time-to-implement vs run-time efficiency.
So they aren't typesafe. Big deal. I almost always put things in collection from within a typesafe member function, so this really doesn't bother me. Having to cast to the type I'm assigning is annoying, but that is is what dyn-abrevs in emacs are for.
I can't stand C++ and all of it's boroque(n) splendor. STL is just another layer of obfuscation.
I once tried using C++ STL for a programming competition. Had to write a simple HTML parser. I wrote the thing and it gave me a tonne of indeciferable error messages. Spent the rest of my time trying to track them down. It always felt like I'd have the thing done in a few minutes, but it turned out I had no idea what I had done wrong.
...so I never moved on to other questions, and got a terrible score. I now hate STL with a passion. (Actually I don't use C++ anymore...)
The opinons expressed are those of the voices in the author's head and are not necessarily those of the author.
First off, I would like to say that the general
_ complex)*some_int);
...
... the ISO C++ 3.0 doc does NOT cover all the necesary functions, of if it does, its so disorganized that I don't understand it
system is great, but there are a few _very_ dangerous bugs.
Bug 1:
list myList;
list::iterator myIt;
for(myIt=myList.begin(); myIt!=myList.end(); myIt++) {
if (something about (myIt)) {
myList.remove(myIt);
}
}
-- run that above, and you'll get seg faults in _weird_ places, like a few iterators down the road -- i have no clue why.
Bug 2:
class something_complex{
list blah;
}
something_complex *ptrs;
int main() {
ptrs*=(something_complex*)malloc(sizeof(something
ptrs[0].blah.someoperation;
}
also gives a seg fault
lack of good doc
FXFX
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.
The STL is great, but it can be a bit of a pig when it comes to compile time. Heavy use of the STL ends up roughly doubling our compile times... even with very careful dependency manipulation. There is no good way to forward declare complex template declarations, so you usually end up including the stl headers in your .h files instead of in your .cpp files where they belong.
There are some very clever template expansion tricks that can be used to do compile time calculation of certain mathematical functions that end up really inflating compile times as well.
A really good tip for improving compile times is to search the stl headers to find their header guards (e.g. _STRING_, _ALGORITHM_) and in your code, put:
#ifndef _VECTOR_
#include
#endif
Even though the code in the header does not get compiled, it still has to be parsed to find the associated #endif. Wrapping your own #include is much more efficient.
Yes, yes, yes, I know it does not work on across platforms, but it does not hurt the other platorms either, it just works like normal.
Jens Wessling
is that STL "IS NOT PIRACY"
I think we all need to get CmdrTaco to impliment a post annotation system. Something like this was talked about back in the days of the Troll Post Investigation. We really need the capsity to go back and ammend posts!
Why bother.
> 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).
I heard that there's no sparse matrix (or any sort of matrix) container in the STL. Where would one go for that?
Chris 'coldacid' Charabaruk Meldstar Entertainment
well, almost!
I have to say RTFM. BUG 1: Your iterator became invalid once something was erased. In the specs: "List reallocation occurs when a member function must insert or erase elements of the controlled sequence. In all such cases, only iterators or references that point at erased portions of the controlled sequence become invalid." BUG 2: There's not enough information, but it doesn't look like an STL issue. As for the docs, I have seen several good sets of documentation on the STL.
//TODO: Think of witty sig statement
Not disagreeing, but I've seen some compiler errors from straight C compilers rivaling that obfuscity. These are usually arising from the agressive use of really long complicated macros. This makes since when you consider that macros are used to acheive the some of the same functionality as templates in C++. Without the type safety, of course.
XML causes global warming.
Yes, I was referring to binary code, not c++ code. I really should double-check my posts for clarity.
Apart from a bit of time you need to invest in learning how to properly use STL, I don't think there are any downsides. There are many ways you can write inefficient programs, using direct assembly language...it all depends on how good you implement your solutions. STL is a powerful tool that should help you, if you learn to use it well.
While we are on the subject of STL, I'd like to recommend "stlport" (www.stlport.com). It is a somewhat more efficient implementation of the STL and works with most compilers (I have used it successfully with MS-VC++ 6 and Borland C++ compilers).
It would be nice to do this:
//...
std::vector v;
typeof(v)::iterator i = v.begin();
local typedefs are a workaround, but are wordy as you say.
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.
When things are working as designed, the STL can save you a LOT of headaches. But when something goes haywire, are you going to be able to debug the problem in the function named:i ngZt4pai r2ZCt4pair2Z6stringZ6stringZ7mapelemZt9select1st1Z t4pair2ZCt4pair2Z6stringZ6stringZ7mapelemZt4less1Z t4pair2Z6stringZ6stringZ5allocPt14__rb_tree_node1Z t4pair2ZCt4pair2Z6stringZ6stringZ7mapelem
___erase__t7rb_tree5Zt4pair2Z6stringZ6str
This is how many STL function names will get reported, if you don't have a really good C++ name demangler (and yes, this is an example from a project I'm working on). Note that the problem might not be in anything in the STL, but a memory corruption could easily flatten something being managed by STL code.
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?
Some things simply cannot be managed appropriately by STL containers. For example, never try to use vector<auto_ptr<string>>. The semantics of the copy constructor of an auto_ptr are not compatible with the requirements of an object to be contained by an STL container (specifically, the copy constructor has side effects).
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
Scientific programming is slowly coming over to C++ due to the vast power of its template meta programming. BOOST is awesome. It matches or beats FORTRAN's BLAS in most tasks. No other computer language has anything nearly as powerful as C++ templates.
If anyone even mentions Java in scientific computing circles they'd get laughed off campus. FORTRAN or C++ is used exclusively in this area.
I think the problem has to do with the macro-esque nature of templates -- where it finds the error is buried in some symbolic expansion that does not back map to tell you what you did wrong. In an unrelated topic, LaTeX (a bunch of TeX macros) has much the same unfriendliness to its error messages.
For error handholding, interpreted good, anything macro'd or templated, very, very bad.
I've been advocating the use of STL on almost every project I've been on since 1998 - it really sounds like a great idea - and STL has paid me back with portability/upgrade problems almost every time.
STL would be great if it actually worked between compilers/OS versions, but I still feel like I'm running a risk whenever I go for a solution based on STL instead of coding everything from scratch in C.
/Snebjørn
Faster-Harder-Louder
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.
Yeah, I figured you probably knew what you were talking about, but was not at all certain that everyone else would.
;)
No need to check for clarity, that's what I'm here for
"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.
Usually (but not always) only a problem when you are doing server side work but RWCString uses copy on write (see here). You have to muck around with the mutex pool size to really get this to work though...
I am not a number! I am a man! And don't you
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
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.
GJ is that language, A Generic Java Language Extension . Note that the page contains this link, Sun has put forward a proposal to Add Generic Types To The Java Programming Language, based on GJ.
I first came across GJ in an article, GJ A Generic Java, in the February 2000 issue of Dr. Dobb's.
BLITZ++ is the math library - not Boost.
I'm such a fucking idiot.
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?
There was an article in the C/C++ Users Journal a year ago testing for compiler conformance. No compiler made 100%. The areas that some of the more advanced compilers lack are probably deep, dark recesses of the STL you'll never use, but there are still gaps in the implementations.
Why not declare iterator as a typedef in MyClass?
typedef vector::iterator iterator
in a public section of MyClass.
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?
I have just one thing to say that makes working with STL a rather intimidating experience initially:
4786
They were great back in 1993, but have done little to keep pace since them. They even broke the APIs of their own RW container classes between the STL and non-STL versions of their Tools. Does that make any sense at all? Their libraries are supposed to _shield_ me from changes - that's why I paid big bucks for their libraries in the first place. Who gives a shit if I happen to use STL or not - why are the arguments to their classes different as result of configuring with STL or not? I should not _change_ my code when I upgrade their library. As such, they add little or no value to the enterprise. They rely on thier customers to find (and sometimes fix) their thread bugs. Now they want a per-program and per-developer and per-CPU royalty - forget it. Thanks for all the memories!
iterating over a map is about the same cost as iterating over a list. A map is derived from a Set, which is pretty much a sorted list with an added hash table for quick lookups. The performance hit on a map comes on insertion which is much slower than inserting into a list.
While I agree that the standard interface hides the complexity, I personally think that's a good thing. The bulk of the code written will be of a run once variety, whereas a central core will most likely require custom code anyway, indicating less of a need for a "standard" library.
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
One project I'm working on uses STL for containers while OpenC++ writes the stream insert/extract. The result is too beautiful for words, but one day maybe you'll be able to play it :)
Not necessarily. Just consider the alternatives to templates and forget for a little moment about being enforced to templates in C++ because of a missing general base class (like Object in Java). If you have templates, you will get duplicated code for each different template instantiation. Code duplication, however, does not happen if you write some general code that works for some base class. Take List in Java, for example. You have the code of List just once even if you have several lists, one with apples and the other with bananas.
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.
Know why I like Java?
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.
There is NOTHING that can reach the speed of C/C++ code.
I don't like every feature of C++ either, but it's not _that_ bad and the STL is very good for the most part. If you are working with any type of application that requires maximum user responsiveness or pure computing power then you can NOT beat C/C++. I would argue that every application should run at near the maximum possible speed afforded by the computer, I'm sick and tired of waiting on the computer to do stuff.
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.
Does anyone have links to good implementations of smart-pointers?
Yes, yes, I know all about the Boost C++ stuff, I'm looking for other (possibly better) implementations.
I need high performance.
Templates and other C++isms lead to write only code.
Don't use templates.
Don't use implimentation inheritence.
Don't use operator overloading.
Otherwise your code will be an unmaintainable pile of shit.
Look at openh323 for an example of this.
WARNING
Debugging STL errors can cause fatal heart diseases.Health Canada
I'd rather be sailing...
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 work for a large firm (~800 employees) of which about 30 are full time software professionals.
...
/LISP knows about lists and hashes. They can be ued in peace.
.... i not well commented .... is hardly transparent either.
I find that one major issue with using STL is that is not part of the C++ "language". That means that someone who says he/she knows C++ does not necessarily know STL.
This means that I have to avoid using the STL when my code is likely to be modified, read, fidddled with etc by other folk on the team.
This gets done qutie a bit and more importantly will be done when I leave the firm
In the case of say Perl or LISP (which admittedly do not compare directly) you get Hashes and Lists as part of the language itself.
Thus anyone who says he/she knows Perl
Further having a list/hash as part of the language itself would possibly mean a significant reduction in the size/style of error messages and the like.
I still use the STL whenever I can and hide behind interfaces (when they can be well defined in advance) or when working on small individual projects.
While I cannot say this with any real confidence, I think that understanding why someone's chosen to use container x and not why
Does anybody here have comments about the state of generic programming in Java? I know a bit about GJ, but that's about it.
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.
Sun is working on adding generics to Java, hopefully by JDK 1.5.
Asside from the code bloat and lack of control over memory allocations, a big problem I've had is working with programmers (usually fairly fresh out of college) who were taught how to program with STL and we find that they can't program without it! They are too used to the hand holding and don't know the algorithms they are using to begin with. I also grit my teeth every time I hear the "never write a linked list again!" quote... that dismays me every time! I wrote my last linked list (in C) back in 1985- and I've been using that "linked list management" code ever since. It strikes me that when people learn something like STL, they shut down their brain from ever thinking about the problem that STL was created for in the first place. A long time ago I built a set of "personal programming" routines that handles everything that I encounter during my programming. I understand this logic and I can fix and extend it as needed. People that start with STL never get to develop such expertise over their "bag of STL tricks" since they did not write it to begin with, can't debug it even of they had to and find themselves shit out of luck should they find themselves in an environment that does not have "their" STL implementation.
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.
Code bloat need not be a problem of using templates. If you look at
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.
Cheers,
Bjorn De Sutter
Ghent University
Are there any real practical compiled languages out there other than C and C++? serious question here. I want to write a fairly high performance app, what lang do I use? C isn't that great to be fair, it's standard library is a joke and doing tons of memory management isnt really up my street. This leaves the lesser of two evils C++. Java is... not that great cause it takes forever to load and tons of stuff is done on the heap (please don't flame me Java programmers, for now all I care about is that most people regard Java as slow whether or not that's justified ... that and it's controlled by one company anyway which I dont much like either). Python and Perl require interpreters so you need to have the whole shebang installed on the client's system and... well, let's be frank here it just looks extremely unprofessional if it isn't a CGI script. Someone hit me with a clue-by-four if I'm talking out of my arse or if not, tell me what decent compiled languages exist out there =)
Dinkumware, Ltd. was the company that Microsoft contracted with to write the library files for VC++ 4.2, 5, and 6. Due to a lawsuit involving Dinkumware and not Microsoft, the library was not updated beyond the July 1996 draft standard until VC++.NET was released, which was after Dinkumware trounced Plum Hall, Inc. in that lawsuit. By the way, Dinkumware has a page detailing all the known bugs of the July 1996 draft implementation and how to fix them here.
It occurred on line 109 of readply.cpp? Now I'll grant it took 30 seconds to decode, mostly because you appear to have lost some characters in posting to slashdot and the character wraps at odd places.
The really hard part was finding the 'to non-scalar type' in there to find the start of the second type. It isn't hard once you get use to it.
Kirby
STL is useless for Windows programming for two reasons:
1. Many of its classes that input or output strings are only designed to work with ASCII. If you want to do anything with Unicode, forget it.
2. std::basic_string has no CASE-INSENTIVE comparison routine. This is absolutely necessary for doing anything with Windows pathnames. Again useless.
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.
Too many slow Java casts. The IBM Jikes VM (formerly named Jalepeno) gave up on GCJ because it produced too slow code. They hand roll their own Java templates with a custom utility they wrote.
By the way, GCJ cannot templatize builtin types (such as int) which makes it completely useless for any serious development.
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.
The big disadvatage of the STL, try reading the source to find out what the bug is, or just how a certain part works.
I've seen deliberately obfuscated "C" code that's
clearer.
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!
he pretty much states clearly that he is an ignorant monkey in no position to pass judgement, got to love slashdot!!!
That is your private terminology but not that of the field. The final phase of a compiler is called code generation and the result is code. Yes, code has multiple meanings and this is just one of them. For this reason, compiler writers (like me) prefer to speak about source text for the input of a compiler to distinguish it from the code which is the preferred term for the output of a compiler.
And if you don't believe me, look it up in the Jargon:
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.
Come on...if you compare the STL to Java for most programs, the STL wins hands down. Ever looked at the consistency between the Java classes that Sun supplies? Class A will have a method called M1 that does something and class B will not have a method called M1 but instead called M2...and both do exactly the same thing! Did Sun assign each programmer to a class and have them write each one without talking to each other?
I actually use Java for some things, but with the class documentation open in a web browser at all times since it's so hard to remember the inconsistent naming. I think they should just deprecate half the methods, switch to common names, and then actually remove deprecated methods after they've been there for several releases.
I'm curious about peoples' experiences with exception-safety in various STL implementations.
If during some operation an STL function calls your code which then throws an exception, do STL implementations guarantee integrity of any data structures that might have been in an "in-between" state at the time the exception was thrown?
The only problem with STL and C++ in general esp. by judging from what I read on here is the lack of qualified programmers.
One downside of the C++ STL is that it is not Delphi's VCL.
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
Not exactly the same thing, but I read recently on the boost mailing list that someone had created an extention to gcc that allowed him to 'instruct' the compiler to not emit these awful errors. So instead of a couple of pages of error messages that essentially tell you that you have not defined operator== (or something that trivial), you get a single message like "need to define operator== for class Foo when passing it to library Bar"
It was very cool and people seemed to like it. Let's hope that the standards body considers something like it non-intrusive enough to include. Of course someone would have to actually write up the proposal, too. So it may remain a gcc-only feature, if it even appears in mainline gcc.
Real Men also choose to program in Perl, in order to ensure their job security, and then pose as if that makes them studly. In short, Real Men are morons.
That's why more women should be working on software development projects.
what about:
//whatever
;-)
class myclass {
typedef vector::iterator iterator;
}
should work rather nicely
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.
cat>Hello.java /usr/local/jdk1.3.1/bin/i386/native_threads/j ava -cp . Hello
import java.io.*;
public class Hello {
public static void main(String[] args) throws Exception {
System.out.println("Hello");
new BufferedReader(new InputStreamReader(System.in)).readLine();
}
}
javac Hello.java
java -cp . Hello
Hello
^Z
ps x|grep java
coward 19341 0.7 1.9 170272 7548 pts/0 S 02:01 0:00
eight repetitions of former snipped due to lameness
coward 19386 0.0 0.1 1364 452 pts/5 S 02:02 0:00 grep java
Wrote 25+ KLOC application in it - never again. If you want to use several libraries in your code (which you do, since reinventing the wheel is not in your job description and is boring), these libraries demand seemingly incompatible compiler flags. So, building all library variants - static/shared/repo/optimized becomes a major PITA.
Then you want to migrate from Solaris to Linux, and you have to fiddle with the code again, because Linux versions of all libraries wouldn't compile with -frepo.
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
Believe it or not, eventually you do learn how to read them without much trouble.
This is quite true. For whatever reason, my eyes very quickly bounced from "conversion from `_List_iterator" to "to non-scalar type `list".
That basically tells me all I need to know, along with the line 109 of readply.cpp. Maybe it is just mental training, but the STL errors that g++ generates are workable messages. You just need to get used to finding the relevant information.
Of course, I try to stay away from C++ anyway, and stick to C, but that's just personal preference for the most part. The real smart thing is to use the tool (language) that fits the problem best.
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
The "eight repetitions of former snipped due to lameness" is not java's fault but Linux Threads fault.
Get a real kernel.
i have used python in production environments since 1997, i use java for the most part right now. i have NEVER had a problem with tabs messing up the flow/ parsing of my code in python.
...if you insist on C/ C++ you are doing a dis-service to your clients.
some of your points are valid but the same can be said about assembler; a human can write better assembler than GCC.
i guess it comes down to if you want to program to satisfy your ego by doing it 'old school' or if you want to get business functionality out the door. if you're writing device drivers and intensive number crunching then C/ C++ is your thing. but if you need to slap together an app to get it out the door and in front of users, Perl, Python, Java are great tools
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));
ok. what was i thinking. 9 threads for helloworld is completely reasonable after all.
> 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.....
For a person who plays Unreal, I've seen such statements now and then:) Only now, you've taught me thats its a STL template error. ooooo aaaahhh!
I see a lot of people are bitching about the template expansion and how incomprehensible it is, I agree (I've had my share of problems), but it comes down to the way the compiler displays this information, this can be solved easily if the compilers output could be made graphical in some way to aide interpretation, eg. branches of instantiation to show clearly the point of error and the path it leads down. On the other hand, I strongly disagree that templates in C++ are incomprehensible, that all comes down to the writer and the syntatic sugar, you can't blame the language when it is the writer who made it look awful. template const my_type returner( const my_type* const object ) { return *object; } I find that much more readable than writing an overloaded function for every single type that could be used.
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.
> Take List in Java, for example. You have the code of List just once even if you have several lists, one with apples and the other with bananas.
And, in Java, you can have a list containing both apples and bananas, even when only apples was intended. The compiler doesn't help - you have to write runtime type checking code, or wrap that generic List within a type-checking outer class; voila', templates!
Now you know why generics are being added to Java.
Suprise! Java wasn't engineered for "Hello World" applications. You're forgetting that there's a VM and a compiler loaded there. Please show us the size of your GCC, and the differences between the Java bytecode and the native binary.
<Amanda`> I just went out to the parking lot in my bathrobe to exchange warez CDs.
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 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. Lisp has the same syntax for macros as it has for any of its code. If your project depends upon the genericity and data collection that STL provides then you probably would be better served my Lisp (IMHO). Obviously, if you are at a business where C++ is required then Lisp may not be an option for you. But if you have the freedom to make language choices, check it out. http://www.alu.org
The biggest issue with any C++ 'standard' library, is that every compiler vendor has to implement the standard. Leading to incompatibilties and wasted resources.
What C++ needs is something like Java. a standard reference implementation that all licensed compiler vendors can resue. If all Java compiler vendors had to rewrite the standard Java libraries, it will take thousands of man hours and introduce all sort of bugs. Atleast bugs in the current Java implementation are isolated and reasonably well addressed.
I am glad that we switched away from C++ to Java for our server implementations. Will never look back.
While I often do "slap togehter" code when I know I am going to use it onece and throw it away. Or when I am prototyping it...
It is intrinsicly evil to *DELIVER* "slap together" code.
The median case, where you are safely within bounds is all well and good, but if you deliver actual product that has to run dangling-anatomy-to-the-wall for months you had better not be slapping anything.
[begin steadly increasing rant/troll]
I do not do things "old school" for ego's sake. What a pitious reason to do anything. I do things 'carefully' and 'with the correct tool for each job' because I can not STAND to have to go back and do the same job more than once. My opinion might differ if I were "a consultant" where my big dime came from return visits to do maintenance. Then again, probably not, doing inferior work to keep a job alive is dishonest and goes against my work-ethic. I consider my code like furnature. I make a chair I am done with that chair. Going back and re-making that chair when I could be making coffie table or a new and better chair would be stupid, boring, and wasteful. I also {GASP} reuse my own code in later projects because, having made a chair it would be a shame if it was only sat uppon one time.
The web and the "e-economy" has gifted us with a lot of truely sub-standard programmers. Part of this is the inherent nature of CGI. (It's one invocation one action nature allows some truely horrific code to "work well enough".) If every invocation is atomic and it sometimes fails, the user hits reload. If their dataset always fails then that user doesn't come back, usually without complaint.
That screw-the-boundry-case mentality is real business to some folks, and those reloads and abandons actually cost tiny amounts of money, not so tiny when it is considered en-mass.
To your particular bragg: I am very happy for you that you have never had a white-space error mess up your code. Hurray for you. [Not that I actually beleive you. Perhaps you have never had a "tab vs space" mess you up, but when you hold that statement up as a "glittering generality" (= look it up, or ask your lit professor 8-) you will be evaluated in the general case...] Pitty the poor bastard that has to deal with it (the source code) later, especially if gets passed to him via email or MS-Office.
I am sure in my soul that someone somewhere has made the same claim of "never having had a problem" with respect to his RPG code too. It still doesn't make whitespace a valid control structure that a sane person would want to use. "It is perfectly safe as long as (your condition here)" isn't a good argument for desireability, only acceptable necessity, and it WASN'T NECESSARY.
Was saving the one keystroke (the close brace) per conditional block really that valuable compared to having to mess around with all the "special" Python-friendly editors? How about the number of times someone has has accidently mis-indented a statement?
Was that value?
Was the wasted time spent to the greater good?
Is the counting-spaces durring each compile an asset?
Computers are damn fast these days so most people don't even sneeze over wasted cycles. It's sad. One wonders how much faster and better any given program might be if the programmers still thought of one machine instruction cycle as a valuable resource.
Game programmers understand, engineers understand, batch-process workers (banks etc) understand.
Anybody who has ever had to maintain code understands.
But I guess we are all wrong... your five whole glorious years of *occasional* Python use has enlightened us all to the folly of our conservitive attitudes...
Meanwhile you keep slapping together those deliverables and we will bask in your magnificence.
8-)
Innocent people shouldn't be forced to pay for inferior software development.
--"Code Complete" Microsoft Press
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
Sure, you can do this. But do you really want to leave the type system even for a list of bananas or apples? One important reason (among many others) to use templates in C++ is to survive the absence of a general base class without giving up type safety.
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.
This was not a discussion whether we want to use templates or not but about how expensive they are. Templates cause more code to be generated for several instances of lists than Java where we have just one piece of code handling all lists. That the lists of Java do not allow you to restrict a particular instance to bananas is nothing new. Nor is the discussion about OO techniques vs templates / generics something new. That discussion was already started long ago with the paper ``Genericity vs Inheritance'', SIGPLAN Notices, vol 21, no 11, November 1986, by Bertrand Meyer.
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.
This interview with Alexandre Stepenov is pretty amusing. He apparently calls OO programming "a big hoax". He also states "quite clearly that Bjarne [Stroustrup] is the preeminent language designer of my generation."
A very interesting read.
http://www.slac.stanford.edu/BFROOT/www/Computing/ RWmigration
http://lnxatd01.cern.ch/Atlas/DaqSoft/rw2stl
Enjoy!
No, this is not a bug. There won't be any bugs if you do it correctly. Just make sure that the derived class doesn't need a destructor, and don't use any virtual functions, and you'll be totally safe.
It's not "bad design". It will work just fine (and safely) if you know what you're doing.
It doesn't make any sense to criticize the design of a working class just because someone *might* add some code to it in the future that *might* cause it to break. If that was a valid criticism, then every single class in the world would be bad design.
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.
I agree with some of the other comments on this thread. The STL can be hard to learn, the error messages generally stink (but that's really the compilers rather than the library), and it's easy to get yourself in trouble because of the complete lack of error checking. I also agree that people who only learn how to write C++ programs with the STL and don't know how to implement any of their own data structures or algorithms are going to be pretty useless when they get out into the real world.
All that said, however, I believe it has a very important role in allowing highly efficient programs without locking you into one particular data structure or algorithm. I just think it should be kept inside user-friendly classes rather than put in the main program, if you have a choice in the matter (and you almost always do).
Before I would teach someone the STL, though, I would make sure that he understood the basics of C++, like variables, classes, inheritance, and polymorphism. Then he would be able to use the STL and a productive way without being overly dependent on it. After all, you can't expect every algorithm for data structure you ever need to be provided as part of a standard library.
By the way, if anyone is looking for a good C++ programmer, you may want to look here.
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.
Has anyone faced problems with queue push_back() function in a multi threaded program, multi processor box?
Has anyone faced problems with queue push_back() function in a multi threaded program, multi processor box?
I'm running out of memory...
The great power of the template engine is specialization and pattern matching. This allows compile-time functional programming, known as template metaprogramming. Metaprogramming provides all sorts of cool possibilities, including program generation, type-safe, compiler-aware conditional compilation, blazingly fast numerical computation and embedded domain-specific languages. For examples of the latter two, check out Blitz++ and Spirit, respectively.
First of all, you have to make sure you turn off syncing with stdio. This prevents you from mixing iostreams toghether with printf/scanf but it speeds up things a lot.
Second, gcc's c++ libraries threw away their internal buffering becuase noone stepped up to maintain it. So, it's not exactly the language, but still there's room for improvement.
(* 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.
Or you assigned your apples:
std::list::const_iterator
to non-scalar oranges:
`std::list'
Which is, of course, why I didn't say it.
XML causes global warming.
While, in general I like the STL and I use it often there is one design flaw that makes it unnessasarily more difficult to use. An STL container iterator can only be defined if you have a complete definition for the object which you wish to contain. This means you need to create an extra set layer of classes if you want an class to contain an iterator to itself.
you want a real programming language, use Objective C on Mac OS X. Much much better than than c++. Trust me.
It has much more power than Java. It has all of C's speed. It is much more object oriented than c++ will ever be.
Objective C!
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!
http://www.bdsoft.com/tools/stlfilt.html
.99 for g++ (4/11/2002)
Works pretty well, available for lots of compilers!
The above example boils down to:
BD Software STL Message Decryptor Release
readply.cpp(109): conversion from `iter' to non-scalar type `list' requested
Don't Panic...
Oops, you're right. I missed "some of" in your original message. My apologies. It's been a late night of hacking. :)
You should never inherit from a STL container? I've read a whole bunch of C++ tips and guidelines, but I've never seen that one before. Sure, you've got to be careful about the virtual destructor thing -- but that's true for all classes. You say that warning like you've had some horrible experience with it. But I've done it a few times, and it seemed to work ok. I read this whole thread, but I still don't see why the STL classes are worse base classes than other classes. What's the special case with STL?
I especially like this example:
Yeah, I know that was kind of pointless...
I'm reading this immediately after finishing my final CS2 project, where I was required to use STL containers, and also supply a write-up explaining why I chose such containers.
The assignment itself was a bit absurd (weird, not hard) though... emulating pine on an extremely basic level, ie not really going online, not using ctrl commands, etc etc.
Oh well, at least is was satisfying to have it finished and working.
my $.05
<pendant>
Always use standard C++ headers:
#include <iostream>
#include <cstdlib>
</pendant>
I don't get it. I don't have a destructor in my subclass, so what's the harm? (I didn't use virtual, I just kept it nice and simple.) Please let me know what I did that's not valid. It's working ok, but now I am worried!!!
-- D.S.
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).
Wow - I really hope you don't actually consider Perl to be a suitable alternative to Java, it is a scripting language for crying out loud (and an incredibly ugly one IMHO), I can't believe that whatever magic fairy-dust they plan to sprinkle on Perl6 will change this much.
I, too, have a hard time believe Perl6's objects will beat Java's, but I really haven't been paying much attention.
Calling Perl a "scripting language" just proves you don't know what the fuck you're talking about, though. Perl is a compiled language. It's just (generally) compiled at runtime instead of ahead of time.
There are plenty of reasons to dislike perl, but resorting to lame attacks like calling it a "scripting language" (as though that matters) proves that you don't really pay attention to many languages besides your beloved Java.
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...
Binary incompatibility is a well known and well documented problem. Given your attitude, you will be better served by a language which specializes in late bindings. Late binding is the patron saint for wading into something without first scouting the terrain.
There is now a standard ABI for C++, but it is not yet widely supported. Too many vendors don't regard this as a priority.
The reason that gcc 3 failed is that it is attempting to support the standard ABI. gcc 3 had to change in order to do so.
I'm sure you'll be happy to know that in the case of gcc it was the cure that killed you. OTOH, avoiding VC6 like the plague is not such a bad idea.
... 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.
Ive come across a few issues using STL. Although the benifits more than outweigh the disadvantages. Biggest one is compatibility with vendors, mostly with VC6. Cygwin and G++ seems to work alright, with one exception using the size() function and the capacity() function with vectors, although I cant remember what exactly it was off the top of my head. Some performance loss has been experienced, but only slightly in my case, and code seems to compile a little large for simple programs. And probally the biggest annoyance Ive come across with containers is declaring them. Multiple declarations of container variables across functions will get annoying, I dont think Ive ever used the typedef statement so much until I started working with STL. Other than really simple annoyances, the STL is a great time saver with the containers it provides, and the iterators make working with pointers a breeze. I havnt so much been very impressed with its Algorithms, but then again I havnt really come across much of a need for them either, although there are some good ones. Other than vendor specific issues and minor annoyances, I dont really have anything real bad to say about the STl.
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.
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?
That must be the San Francisco-based subsidiary of Rogue Wave, right?
We used STL in a large project and ended up rewriting all parts that used STL because of two problems: One is that a lot of STL implementations - specifically the one that comes with g++ aren't thread safe. Supposedly stlport is thread-safe, but then their iostreams library isn't (but g++'s iostream library is - so you _can_ get it to work). Secondly, it is a pain to debug. Write your own template-based lists, hash-tables etc. and slash your time spent debugging by an order of magnitude. If you use STL and you're like me, most of your bugs will be related to data-structures that you use STL for, and that is exactly when you don't want to wade through the complexities of your STL implementation.
Just my 2 cents.
Probably because it does not support precompiled headers.
Writing STL-style iterators is, in my opinion, an enormous pain in the ass, involving lots of tedious coding.
... or half an hour's worth of less tedious coding using the Boost iterator adaptor library?
here's my short list of STL problems:
- decent pointer support missing (who wants to copy objects, large or small) -> usually ends up
extending the STL with home grown untested extensions
- missing single linked list, double linked list in std::list is an overkill, std::vector is too little as a container
- on the other side, who really needs a std::deque
q.
Sorry to put it this way, but you have butchered/misunderstood what Myers says.
:-)
Actually, I bet you've been bit by HTML syntax, which renders plaintext invisible. Here's to proofreading
Neither Myers, nor any other proficient C++ programmer, would claim that vector is an ill-conceived specialization and not a container. What he says is that vectorbool is an ill-conceived specialization and not a container.
vector is a well engineered general container, and an excellent replacement for C arrays in most cases (C arrays are Bad Things in general). vectorbool is a specialization of conceived in such a way that it doesn't even behave like a vector. It is bad.
I can't see why the STL errors would be any reason for any grif, makes all perfect sense to me! ;-)
Mind you I use a BrainFuck precompiler since I refuse to program in anything less than the one true language one should use...
disclaimer: I'm just trying to be a bit funny, ok?
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
The new language you're looking for is lisp/scheme
e.g. Common Lisp macros have supported a clean form of generic programming forever.
Of course using dynamic typing helps too.
I found STL very useful. I would suggest these things first:
1) Take the time to learn it (write some 'toy' programs, and experiement. I took about a week).
2) Get a good book, and read it. I looked on amazon for the user discussions, then bough at bookpool.com to save a few $$$. I use the book "STL Programming from the Ground Up" by Herbert Schildt.
3) Research the known bugs for your implementation of STL. VC++ has several, one that stumped me was the use of my own sort function (funtor) in sorting a list of elements. As I recall, VC++ will not sort more than 16 elements (VC++ 6.0 SP5), so we had to call an internal reference generated by VC++ to make it work.
4) If you're using VC++, I suggest you take a look at sellsbothers.com for their tips. I even found a tip on which byte to change in msdev.exe to increase the thread priority of the compiler, to make it compile a bit faster.
5) Talk with the other developers at your work place (or school). They may have insights and feedback too. Also, consider if other people will be using this code, or if it's just you. Sometimes other programmers don't want to learn new things, and your choice of using STL might create a larger problem (social)
Anyway, good luck with it!
Suncoast Linux - Sarasota, FL
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.
The thing I like the most about stl is: I have written 2 large(moderate) projects in stl and I have not used a single new or delete. Therefore there is no memory leaks and associated clean-up work. My destructors are almost always emtpy and my constructors are usually the simple initialization type. Also I have very few pointers. At first I tried to code w/o any pointers but I found cases where I couldn't use a reference and had to use a ptr. For example if a particular variable is optionally valid a ptr is much better(NULL or not NULL). Also any collection of references doesn't compile(correct me if I am wrong).
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.
IMHO the purpose of std::auto_ptr is not smart-pointing but to provide:
/* No delete[] since automatically done by compiler */
/* No delete[] since automatically done by auto_ptr */
void subroutine( int n_dynamic_size )
{
...
float size_dependant_array[ n_dynamic_size ];
...
}
that some compilers such gcc allow. And it is sooo comfortable!... but... sooo un-portable!. The correct code would be:
void subroutine( int n_dynamic_size )
{
...
float * size_dependant_array=
new float[ n_dynamic_size ];
...
delete [] size_dependant_array;
}
and the std::auto_ptr should be something like this:
void subroutine( int n_dynamic_size )
{
...
std::auto_ptr size_dependant_array=
new float[ n_dynamic_size ];
...
}
OK, an smart pointer would do the job but, again IMHO, with a small overhead respect to std::auto_ptr.
c:\program files\microsoft visual studio\vc98\include\functional(86) : error C2784: 'bool __cdecl std::operator &,const class std::multiset &)' : could not deduce template argument for 'const class std::multiset &' from 'const class S'
A while back I came across a Perl script that translated these error messages into something readable, but it seems to be that the compiler should do this for you. Maybe gcc is better...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++. There exist no such thing like a void * in Java nor is it possible to cast something to it. The base class Object is something completely different in Java as you do not lose type safety using it.
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.
Making templates to speed up code seems like a
marvelous thing. Of course, if you REALLY need
this for performance, you are probably targetting
embedded systems, where the code bloat and testing
become prohibitive. So, what's the real difference
between C++/STL and C/M4? Not a hell of a lot,
really (really, truly, equivalent "type checking"
can be done in M4). The syntax is just as ugly,
and the tools are worse.
Of course, templates (STL) are ANTI-object
oriented programming. No factoring, and I must
regenerate code. Wait a minute, if the language
actually supported types as objects, then it
wouldn't matter, the OOP system would take care
of this for me... and it would, except that
C++ programmers (generally) seem far too
concerned about "performance".
Another strike against C++ is the SIZE of the
language. A good programming language reference
manual should be expressible in 12 to 20 pages.
That's it. Anything more cannot be reasonably
used. C, Smalltalk, Eiffel, good. C++, ADA,
Perl, bad. If I can't read it, I can't make
use of it, and its probably easier to rewrite.
If you like C and want OOP, use Objective C.
If you like C and want templates/STL, use M4.
And -- your experience with M4 can be leveraged.
Get this concept: learning M4 (TRAC or one
of the general macro/string languages) leverages
BETWEEN languages. I recommend M4, not because
its better, but because its everywhere. And, you
can use it with C, Assembler, C++, etc.
Ratboy.
Just another "Cubible(sic) Joe" 2 17 3061
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!
With a little practice it's easy. Look at the beginning of the error message and maybe the end. Never the middle. 90% of the time it's invalid parameters (template type vs. parameter type). Perhaps you forgot to add std:: to less in
That one took about five minutes to find because the compile error showed up in something like xtree.cpp. It took a few minutes to discover that it was the map declaration causing the problem. Once you 'grok' the essence of STL philosophy, it's really not any harder than that. My most common runtime error is dtor'd objects in an STL container - so far always my own fault, not the library's.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
I say don't ever step through that stuff unless you're trying to learn how it works. Just look at the parameters to the calls and then look at the results. Lots of times I'll change e.g.
to something like this:
for the simple reason that I can set a breakpoint on the ProcessMine(...) call and see what the iterator is referencing. I put things back when I've fixed the bug. But I do not go mucking around in the STL code itself other than to learn more about how it works. The point is, it does work as long as it's called properly (except when it doesn't, which hasn't happend to me that I know of).
normally the one's you pay for are higher in quality and have more features (such as hashed maps, etc.)
cock munch
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.
Yup. Common Lisp does all that plus everything you reference below... To keep this short(er), search slashdot for Kent Pitman and read his two-postings interview about Lisp. Go to www.paulgraham.com and download his free book On Lisp. Download GCL, CLISP, CMUCL, or Xanalys' or Franz's personal editions and work through every example in Paul's book, typing it in running it until you understand.
Common Lisp compiles to very fast code, Xanalys offers unlimited runtime distributions and, I've been told, very flexible support for what's included in the runtime.
On Lisp changed my programming worldview. I've been programming STL for years but now see large parts of it as an attempt to bring a small part of Lisp to C++. STL succeeds in that, and I do enjoy STL programming. However, why not just use Common Lisp which has all that and much, much more?
Lisp does that...
But the code to make this stuff happen is ATROCIOUS!
Not in Common Lisp, it's not. Define a macro instead of a function and selectively add backquotes and commas. Otherwise, it's plain old normal CL.
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. ...
Lisp does that.
You mention Lisp but you don't mention that Lisp does everything you're asking for. Hope I'm not boring you, and there's probably someone else who didn't know Lisp does all this. In addition, I know that Xanalys in particular (as probably do all the others, with whom I have less direct experience) makes calling OS functions nearly trivial. I've not yet tried callback functions under Windows. Your mileage may vary. I am not associated with Xanalys although I did just buy their Lisp because of the unlimited runtime distribution. I learned Lisp using GCL under Linux. I am not a lawyer. I ....
Sounds to me like it's time for some new language stud to come and save us.
Sound to me like it's time to pay attention to the old language studs. Seriously, with GPL implementation, commercial implementations with unlimited runtime distributions, etc., very fast compiled code.... it seems to me that unless you:
Note: modern editors make the parenthesis comfortable. They are the key to making Lisp extensible because anything following an open parenthesis is a function to be called. Define a function, you just added new syntax to Lisp. You can redefine existing functions, including those in the base package such as addition:and addition is broken everywhere. Lisp is a power tool and should be kept away from children. Use it if you really need to build something incredible.
What other reasons are there not to use Lisp? Lisp has had the features you named as important. Lisp has had them for years. And, speaking as one who has experience with STL, you simply don't need an STL in Lisp. Lisp is truly a giant STL. I don't have to define and name all the miscellaneous little structures I need, I just construct and use them on the fly. Not to mention closures, functions as first-class objects, lambda's (i.e. unnamed functions defined even in parameter lists), macros, run-time typing... the read-eval-print loop for debugging, the ability to replace a function in the middle of a running system with no giant compile/link... geeze Louise it's phenomenal. All those things combined seem to obviate the need for 98% of the things I use classes for in C++/STL. I'll know more after I build something really big in Lisp and have a lot of people using it. I'm working on that...
I enjoy C++ and STL a lot. I'm really looking forward to a lot more finger time with Common Lisp. Don't want to give either one up. But my sense at the moment is that Lisp is by far the more powerful environment. It certainly does everything you mention in your post.
My comments are with the VC6 version of the STL and do not necessarely apply with another compiler.
;-).
:-(. And yes, I know a std::map uses a binary tree structure.
When I first started using STL, I first hated the fact that everything had an underscore (argh!). Second thing that pissed me off was the nomenclature of the methods. For instance, with the stl vector, what did I expect std::vector::empty() to do? I expected it to empty the vector. What does this actually do? It tells you whether the vector is empty or not. Why not use a method called IsEmpty() ? or is_empty()
After this first bad encounter, I decided to give it a shot and started using it extensively whenever I had the occasion. At first, mainly for strings and vectors. I found the iterators particularly fun to use. And now I would never go back to using char * or arrays unless I really have to. Mainly, I love the fact that everything a casual C++ programmer ever wanted IS in the STL, all these data structures you learned in school are integrated AND templatized! The only thing that is not explicitely included are trees unfortunately
After using the STL on projects, I found 2 major irritating things:
1) When you have a syntax error, the compiler lets you know by filling the screen with the function signature and it can be hell to decipher if you're not used to it. And with VC, if you use vectors without a #pragma warning ( disable : 4786 ), the warning the compiler gives you takes 10 lines.
2) Some STL classes do not tranfert good between an application and objects in a DLL. Mainly cause some variables are on the stack of the DLL and cannot be shared with the main application. I think this is a M$ implementation bug specific, but anyway, it can be a pain in the ass to find a solution. usually, you have to use good old arrays and structs to transfert data between the DLL and the main app.
Other than that, after the learning curve is flattened, STL is a great productive tool.
proxima centauri, closest star to our sun!
you don't design neither VM nor language to create a "hello world"-program
"DLL" can pretty much be extended to "dynamic libraries", and STL reflects the general failure of C++ in this respect. C++ was simply designed without the notion that some parts of a program can be reused in the binary form. This resulted in the ABI hell and bloat problems. The strict mapping of source code to binary code, identifier names to linker symbol names, that was essential for C, has been eroded in C++, and no viable remedy has been established as of yet.
My exception safety is -fno-exceptions.
After I sawed off my legs, I still make it fine with crutches and prosthetics.
My exception safety is -fno-exceptions.
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).
Wrong. Their primary objective was automated generation of boilerplate code for COM objects.
For this, I consider templates rather good.
My exception safety is -fno-exceptions.
I realise the question is about the STL, but a lot of discussion has arisen about the failings of C++. I started on C, then Java, then C++, then Perl, M68000 ASM, PHP, blah blah. My favourite of the lot is Ruby. Ruby (unlike Java) has everything as an Object. It supports closures (much neater than function pointers) and has a clean syntax. It adheres to both Least Surprise and DWIM. Generic programming is default behaviour, design patterns can generally be encapsulated in a class and 'mixed-in' rather than requiring code everywhere. mod_ruby exists for Web applications, while Tk, GTK+ and (experimental) Qt bindings exist for GUIs. MySQL and PostgreSQL APIs are available. If you need low-level access or super-speed, C extensions can be written. There are no limits in Ruby - most notably very little distinction between compile time and run time. Ruby is more popular than Python in Japan, I'm told... check it out. There's a free book online.
The funniest thing is that there *IS* a block start character. The colon ":" starts the block. There is also an explicit end of block (the blank line or change of indent). The fundamental truth: Both the colon and the white space *ARE* *EXPLICIT*. See explicit definition 3, if the system can tell where the block ends... And if it just guesses... Or if you put in in wrong...
The block delimits are "less robust" and easy to fsck up but not explicit == implicit (follow the link 8-) either that or Python is a deliberate joke and deliberately "leaves a a question as to meaning or intent." (reverse def #1 8-)
The inventor of Python (and all his parrots) proves himself (themselves) incompetent to talk about language structure or theory every time he says (they say) his blocks are not explicitly delimited.
The blocks are explicitly delimited. It's just that the end-of-block isn't printable or likely to survive being emailed as plain text or posted on the web "casually".
Innocent people shouldn't be forced to pay for inferior software development.
--"Code Complete" Microsoft Press
Thanx for your post - you saved me the trouble of typing in the same stuff!
--Richard
yes i do. simple is beautiful.
...and it has the added disadvantage of objects. Hey, at least its not Java which forces OOP on you instead of giving you an option... and harder to debug...
Objects have saved my butt countless times. As for debugging, objects are easier to debug, in my experience. The codebase itself is easier to understand, better design is possible, and better design makes for easier debugging. All you really have to do to improve performance is limit the number of classes you use. The java platform is a good example of too many classes bogging some things down.
It's possible to write crappy code in any language, under any design method. Objects try to make it harder to design spaghetti code.
It is not just a question about type checking but also of being able to restore correctly the original type in case of a heterogenous list. In C++, dynamic_cast does not work if the given type does not include virtual methods.
This assumption is not correct. A misuse of void *, i.e. a wrong cast does not automatically crash your program. Unfortunately one of the greatest problems with C and C++ is that many problems of this kind are initially survived which, under some circumstances, might open interesting security holes.
Well, I do not consider alternatives that cause me to lose type safety. void * was introduced in C to get rid of char * as a generic pointer type in the context of storage management. It is the correct type of malloc(). Fortunately, we have a new operator in C++ and do not need void * any longer except for some low-level tricks.
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.
To all who want to do anything with STL -
USE THE SOURCE DUDE!!!
And if you are having troubles wading though it all, get gimpel's PC-Lint or Flexelint, and use
it. (you could substitue gimpel's product for
any other static checker)
Honestly, many people love to rush out and cram one library (or language) down everyones throat at a moments notice. The way to become a better developer is to use the best tool for the job at hand.
If I need to whip up something quick, like a splash screen program for Windows, you can bet I'm using MFC. Why MFC? Cause I only need to pop up a splash screen, maybe a dialog box or 2, and I want this thing to be done in an hour.
If I'm designing a new server app, I'm going to sit down and think over what I need to put in it before I jump on any library. (And no, MFC is not my first choice for this.)
Sometimes it's not about code readability, or reuse or even good programming. It's about getting the job, that works to the spec given, done in the shortest amount of time.
Having done a very large, multiplatform (NT and Solaris) project with the STL, the biggest issues we faced were problems with thread safety. Even some of the things that were purported to be threadsafe...weren't. (We found a bunch of bugs in the Microsoft and Sun compilers, and also g++.)
I will say that it enabled us to get a system up and running quickly, but the debugging process (long error messages, obscure thread bugs under heavy load in a distributed system) was absolutely horrible.
Hopefully, things are better now.
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
At least, for the string? What you've written is exactly equivalent to:
std::string foo;
I can see why you'ld want to do that for built in types which aren't initialised by default.
The problem is that std::string doesn't support null semantics, unlike char* - if you want it, there are classes that add null semantics to other classes (I think boost has one).
Does that make it any less useful for you? Jerry
cough*kyoto*cough!
I just feel the need to reply. So many comments I could comment on...
All I can say is "AAARRRRRGGGHHHH" at the script-kiddies , people who tried it back in 1800's or 19whatever and thought the beta sucked, people who looked a book about the STL written by an Ada programmer, "I tried it once and thought it sucked", or people who have only programmed in language and think they know everything about every other language, etc.
It's called get a BS degree in CS from an accredited institution so you actually know some theory. Don't settle for the BA or MIS degree. Apply it. Keep learning so you don't get in the rut of all these people that know it all, they don't, neither do I or you. Actually you should change your programming techniques as technology advances, go ahead try it, you'll be amazed. Much of what we already have learned will continue to become irrelevent, e.g. as HDs go the way of the dinosaur, etc. I personally don't want to be using the same code 10 years from now, forget code-reuse in the long term. As things keep getting faster there will be less and less time to keep "going back to my old code and modifying it a little bit to get it to work with a new " Face it, you don't have the time to mess around with assembly(i.e. old ways of doing things, compilers out code any assembly programmer now), insuring your code will perform to some big-O spec/re-writing the same old code for the 100th time when someone else has already done it for any thing you'll need it for, etc. You need to get it done and move on to your next project. The STL does that today. It will improve like all things. Use it, do it, move on.
Personally I can't wait for Z++ and the SHIL (standard humanoid interface library) in 2015.
I agree with that, and the "typedef trick" is not true encapsulation. But if you "squint your eyes" it works, and I have a hard time respecting people who knowingly circumvent it. People who circumvent it out of ignorance will learn in time :).
Oh, what an interesting discussion :). In my thesis, i'm extending the type-system of a language to include what i call quality-types, which express some quality about a value.
The quality-type in not related to the normal-type of the value.
This can be used to capture predicates such as:
- comes from user input (-> you have to check before you pass a string derived from it to system())
- has security level X (-> you can issue guarantees about the leakage of information)
- ...
example:But, ultimately, a better solution would be run-time analysis, invocable an any time, there are many things you would like to check that it's not possible to check in a static-typed language.
I'm flirting with adding code-anylysis and som type-check like features at "run-time" in a language like python. So your program would start by invoking the analysis, and then proceed. You could defer checking some parts of the program till later, skip the check for efficiency, ... Well, better finish my thesis first :).
I generally believe, that people should code in a language they are proficient with, or get proficient at the language they code in
That said, I don't deliberatly write code in complex ways, but if there's a mechanism that's "best" in my evaluation, I will use it, even if newbie's will find it hard to read. I prefer:
overEvery langauge has a "natural" way in which to program, and it should be used. I write in different styles in C++, JAVA, C, ML, ... I'm don't think similarity in implementation is a goal, although language independence of design often is (because the customer can't decide which language they want implementation in).
I'm not sure I understand... std::auto_ptr is nothing near GC... And it sucks too:
Try looking at http://www.boost.org/libs/smart_ptr/smart_ptr.htm, it works MUCH better.
That's very noble of you, but you are not allowed to mod on a topic you post on anyway :)
SLOGEN [ http://ungdomshus.nu : Sebastian cover music]
The Intel icc implementation is pretty ok. I had no problems using it extensively with linux. I think it exists also for win. It's not free software though...
BUG 2: He's using malloc to allocate memory for C++ classes. Thus constructors aren't being called, so the list member object is incomplete, and garbage. This isn't an STL issue; it's a C++ basics issue.