Slashdot Mirror


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?"

361 of 946 comments (clear)

  1. One Downside by jsonic · · Score: 5, Funny
    but the truth is that I'm a skeptic, so what are the downsides to the STL?

    It's written in C++? :)

    1. Re:One Downside by ajs · · Score: 4, Insightful

      Yes, biting your leg off is much better than putting it into a crusher. Much cleaner.

      However, I suggest using a real high-level language if you want one (Perl, Python, Smalltalk, Ruby, etc) or going low-level if you want that and programming in C.

      C++ and it's less abhorent, bastard child, Java are the ultimate examples of what C isn't good at.

      I'm not trolling here. C++ simply isn't a good language design. It has all the power of C and twice the rope for hanging yourself. The complexity, contradictions and requirement that users understand every aspect of the language in order to program are high on my "why you shouldn't" list.

      Java has only some of C's problems while being totally platform-antisocial (platform neutral would imply that it plays nicely with all platforms which is patently untrue). I will say that Java has one of the best object models of any language out there, but 1) that will change when Perl6 hits the streets and 2) it's somewhat overshadowed by the failure of the Java libraries to live up to the promise.

    2. Re:One Downside by Rorschach1 · · Score: 4, Interesting

      Very true... I learned C originally in DOS and it worked fine there, but I haven't touched it much in recent years. I just recently started an embedded project, and decided I didn't have the patience to use assembly, so I jumped into the world of embedded C for the first time. It's a hell of a lot easier than assembly, stays quite tight with a bit of care (sprintf used up 80% of my available program space), and after dealing with a system having only 192 bytes of RAM and no OS I've got a much better appreciation of how the whole thing works. Stuff that seems like a major limitation after working in other high-level languages suddenly makes sense when you're coding on bare metal.

    3. Re:One Downside by emarkp · · Score: 2, Insightful
      I'm not trolling here. C++ simply isn't a good language design.
      Sigh.

      Q: How many legs does a dog have if you call a tail a leg?
      A: Four. Calling a tail a leg doesn't make it a leg.

      You are trolling here. C++ is good language design, for reasonable different definitions of good.

    4. Re:One Downside by Ryan+Amos · · Score: 2

      C++ was once a poor design. Like all designs, it evolved into at least a workable language. The thing about C++ is that there are a LOT of APIs written in C++ and designed to use C++. C++ is also one of the most commonly used languages, while Perl, Python, etc are more niche languages. Yes, they're used in widespread commercial environments, but not to the extent of C++.

      The problem with the languages you listed is that for the most part, they're scripting languages used via an interpreter. If you need fast execution speed, they're really not the best option. Granted, g++ isn't that great either, but let's not forget the entire world doesn't run unix. There are very good C++ compilers available that optimize much better than gcc.

      Also, as I said above, they're niche languages. If you're writing a large project, you want to use a language that a lot of people feel comfortable with. C++ is pretty much the only language most universities use (some still use C, while some are moving to Java) so pretty much anyone with a CS degree will be fairly comfortable with the language.

      C++ is a very robust and powerful language. The "it's too complex" argument is a poor one, anyone taking on a large project in C++ probably knows what they're doing, and if they don't, well, it'll be a good learning experience. C is very good at memory management in the fact that it gives the user complete control over the entire process. C++ extends on this (not to mention new and delete are much more powerful than malloc() and free(), as they can be overloaded;) being just as low-level as C while allowing the abstraction of an OOP model.

      I do agree that C++ probably isn't the BEST way to do what it does, but eventually the world has to settle on something that's good enough and gets the job done. C++ is not nearly as portable as C, but well-written C++ can be just as fast (or even faster) than C. Knowing a language well is the key to writing good code in ANY language, not just C++. I think it's folly to dismiss such a legitimate language as C++ just because it has a few shortcomings. You probably won't get many jobs with that attitude.

      And hey, at least it's not C#. : ) </ObligatoryMSBashing>

    5. Re:One Downside by jmccay · · Score: 2

      Not to mention that one of the best features about C++ is that it doesn't lock you into one pure design ideal (such as OOP). You can do OOP with C++, but most people I know use a mixture of C and C++ ( a lot of people I know don't use streams for formating because various flavors of printf and scanf are easier to use and more elegant).
      C++ can exvolve to fit a new design ideal without completely rewriting the langauge from scratch.
      Also, like anything you do, you get to know things better as you use them. I wouldn't call C++ a high level language compared to Visual Basic, Python, etc, but I would call it a high level language compared to assembly and assembler.

      --
      At the next eco-hypocrisy-meeting, count the private jets used to get to the meeting. Should be interesting to see that
    6. Re:One Downside by divbyzero · · Score: 3, Informative

      By [at least one logical] definition, a high level language is one that uses constructs which do not map directly to those supported by the hardware on which it is running.

      C is considered [by many] to be a low level language because it only uses constructs which are available on the majority of modern hardware platforms. However, C relies heavily on the construct of accessing the heap. On a purely stack-based machine which has no heap (some embedded systems, for example), you would have to emulate a heap in terms of stacks. C would therefore be a high level language on that platform, while Forth, a language based around the use of stacks, would be low level.

      Sometimes the situation is reversed ... people design the hardware to match the constructs used by a particular language. This was so in the case of the old Lisp Machines, or Sun's picoJava chips.

      Few languages these days are strictly interpreted, as in parsing each line of source code just before executing it. Many are compiled into an intermediate form, sometimes called bytecode. This bytecode, in turn, may or may not be a high level language for a particular machine, depending on how closely its constructs match the underlying hardware ones.

      Even in a purely compiled language without an explicit "bytecode" stage, the further the language's constructs are from those of the hardware, the more instructions it will take to process each statement.

      In short, there are plenty of high level languages which can compile to native code. But this does not mean they will run as fast as carefully crafted assembly!

      --
      But my grandest creation, as history will tell,
      Was Firefrorefiddle, the Fiend of the Fell.
    7. Re:One Downside by Arandir · · Score: 2

      Buzzword bandwagon? What the fsck are you talking about? C++ has been around for about two decades! It's been around longer than Linux and Windows. I think it even predates GNU by a few years.

      Sheesh. Next thing you know you'll be complaining about all these people jumping on the ANSI C bandwagon instead of sticking to K&R.

      --
      A Government Is a Body of People, Usually Notably Ungoverned
    8. Re:One Downside by rjh · · Score: 5, Informative
      I've been using C++ since 1989. I'm still learning more about C++ today.

      It always amazes me at how people who acknowledge they don't know C++/STL (as you said, "I have never used it") know so much more about it than those of us who've been using it since the mid-90s, and who still discover more neat things about it on a continuing basis.

      That said: C++ makes it easier to produce bloatware.

      Two answers:
      • Yeah, so?

        Name me one advance in computer science that doesn't also carry with it the possibility of using the advance stupidly. Yes, if you deliberately do stupid things with C++, you'll get code bloat. But if you make the language impossible to do stupid things in, you'll also make it impossible to do clever hacks in the language. If I want a language like that, I'll use Java, thanks.

      • Have you seen what that `bloat' does?

        Most of the time when people blame code bloat they're really blaming templates. Tell you what: look at the vector template and find out just how brilliantly sweet it is. Now hand-code it in C, such that it gives you the exact same level of sweetness, speed, and safety. Dollars to donuts says your C code is more bloated.


      ... and it has the added disadvantage of objects.

      Spoken like someone who never made it past the introduction of Stroustrup's The C++ Programming Language. Repeat after me: C++ is not an object-oriented language. C++ never was an object-oriented language. C++ never will be an object-oriented language. C++ supports OOP, but that doesn't make it an OOPL. C++ is, more precisely, a multiparadigm language. You want generic programming? C++ has the tools. You want functional programming? C++ has the tools (awkwardly, but they're there). You want OOP? C++ has the tools. You want procedural/imperative programming? C++ has the tools.

      Whatever you want, C++ has the tools.

      Hey, at least its not Java which forces OOP on you instead of giving you an option

      My harsh words about Java (above) were, as I hope the Java community will understand, meant as a gentle jab from one diehard C++ hacker--not as a misinformed flame like you're spewing here. Of course Java gives you an option. If you don't want OOP, don't use Java. Use Ada95 or Python instead, both of which support non-OOP paradigms and which can compile down to Java bytecodes. Java, like Smalltalk, is a purely OO language. Saying that Java sucks because it forces you to write OO code is... well, really foolish. Java doesn't force you to write OO code; you force yourself to write OO code by committing to Java as a platform. Java is a tool in the toolbox. A hammer doesn't force you to treat everything like a nail; but if you choose to pick up the hammer, the only person to blame is you if you needed to pick up the screwdriver instead.

      I can't really talk about the STL

      ... Why not? Your utter ignorance didn't stop you from talking about C++ or Java.

      ... but from the coders I do know who have used it

      ... And are these coders competent craftsmen, skilled in the ways of the STL? Or are they incompetent two-bit fly-by-nighters?

      it is a sad sad mechanism for making your code slower and harder to debug and your executables larger

      Bullshit. Look at the following code:

      /* C version: sorting random 1M-element array */

      int compare(const void* first, const void *second)
      {
      int *x = (int*) first;
      int *y = (int*) second;
      return x < y;
      }

      int main(void)
      {
      int array[1048576];
      qsort(array, 1048576, sizeof(int), compare);
      return 0;
      }

      // C++ version

      int main(void)
      {
      int array[1048576];
      sort(array, array+ 1048576);
      return 0;
      }


      [rjhansen@numbers cpp]$ time ./c_version

      real 0m1.034s
      user 0m0.960s
      sys 0m0.070s

      [rjhansen@numbers cpp]$ time ./cpp_version

      real 0m0.719s
      user 0m0.720s
      sys 0m0.010s


      ... Want to repeat that bit again about how STL causes your code to run slower and be harder to debug?
    9. Re:One Downside by Reality_X · · Score: 2

      What are you on?

      [ok@melchior1 meh]$ make c_version cpp_version
      cc c_version.c -o c_version
      g++ cpp_version.cpp -o cpp_version

      [ok@melchior1 meh]$ time ./cpp_version
      0.52user 0.00system 0:00.52elapsed 99%CPU (0avgtext+0avgdata 0maxresident)k
      0inputs+0outputs (123major+1034minor)pagefaults 0swaps

      [ok@melchior1 meh]$ time ./c_version
      0.49user 0.00system 0:00.49elapsed 99%CPU (0avgtext+0avgdata 0maxresident)k
      0inputs+0outputs (79major+1546minor)pagefaults 0swaps

      C version is faster.
      And that's not even the point (although your "statistics" are obviously false.)

      Let's fix your C up a bit:

      int compare(int* first, int *second)
      {
      return *first *second;
      }

      [everything else is the same.]

      [ok@melchior1 meh]$ time ./c_version
      0.40user 0.02system 0:00.42elapsed 99%CPU (0avgtext+0avgdata 0maxresident)k
      0inputs+0outputs (79major+1546minor)pagefaults 0swaps

      Wow. Even faster.

      Plus, you don't know which type of sort those 2 sort functions actually use. So your whole example is stupid.

      Meh.

    10. Re:One Downside by rjh · · Score: 2

      What are you on?

      ... A heavily-loaded dual P3/800, 1G RAM, which was at the time doing other number-crunching in the background.

      If you think the C version is faster, I must suspect that you're the one falsifying scores--because you've got at least two extra pointer invocations which the C++ code doesn't, due to its aggressive inlining.

      Insofar as what sort those two sort functions actually use--according to spec, qsort() is always a quicksort. The STL sort()... who cares? Implementation detail. I believe it's a tuned mergesort, but I could be wrong--the spec says it's O(n logn) for the best- and average cases, O(n**2) in an extremely unlikely worst-case.

      If you need a better worst-case, stable_sort() is available. Guaranteed worst case of O(n logn logn) and best-case of O(n logn) for any system that's got RAM to spare.

      Of course, you could've found this out for yourself if you'd bothered to spend 30 seconds checking out a spec.

    11. Re:One Downside by Anonymous+Brave+Guy · · Score: 2

      I'm sorry, I'm going to feed the troll-in-denial. ;-)

      However, I suggest using a real high-level language if you want one (Perl, Python, Smalltalk, Ruby, etc) or going low-level if you want that and programming in C.

      I write higher level code in C++ every day than any Perl or Python I have ever seen. I rarely need to use pointers, primitive arrays, casts and all the other yuck that is so often criticised. Instead, I use easy, flexible, high level interfaces to problem-based tools that are implemented using the primitive features if you go down far enough.

      C++ simply isn't a good language design. It has all the power of C and twice the rope for hanging yourself.

      C++ has a great language design. Sure, it has its flaws, and they are many. But as a workable, productive development tool, it's proven its worth many times over. Python and Java have their merits, too, but get back to us when either makes it to its 20th birthday, and about 1/3 of all programmers in the world know them and have used them.

      A fairer version of your claim would be, "C++ has much more power than C, twice the rope to hang yourself, and provides an axe, scissors and lighter to weaken the rope so you can't actually do it."

      The complexity, contradictions and requirement that users understand every aspect of the language in order to program are high on my "why you shouldn't" list.

      That's interesting; I could have sworn that one of the fundamental principles underlying C++ was the "zero overhead" one, where if you don't use a feature, it doesn't hurt. I'm sure I remember something about keeping the feature set orthogonal being another one, too. Maybe it's just me? Oh, no, sorry, I just read D&E.

      You really should get the slightest clue about a language before blatantly having a go in front of an informed audience...

      --
      If you disagree, post your argument. (-1, Overrated) isn't your personal censorship tool for views you don't like.
    12. Re:One Downside by ajs · · Score: 2
      I write higher level code in C++ every day than any Perl or Python I have ever seen.
      Wow, you've seen some pretty sketchy Perl and Python. Try this in C++:
      use LWP::Simple;
      print join "\n", map {(get($_) =~ /(stuff1).*(stuff2)/si)} @urls;
      This is just a dumb little example that fetches Web pages, but in this one example we see the vast grammatical advantage to working with truely high-level objects instead of C++/STL's low-level constructs.

      For those of you in the cheap-seats, this:

      • grabs the libwww-perl module "Simple",
      • fetches a list of URLs (using the HTTP "GET" method),
      • searches the content of each result for two strings, and
      • prints out all of the resulting matches.

      C++ has some nice features that begin to appoximate the power of high-level languages, but let's not start to pretend that that makes it as powerful as a truly high-level language.

    13. Re:One Downside by ajs · · Score: 2

      Since many people have responded, and most of those have assumed that my "I'm not trolling here" was intended to be an introduction to a carefully crafted troll, let me just set the record straight.

      I program in C++ when I have to (though, I'm by no means an expert). I'm also a C and Perl programmer.

      I don't hate Java, I just think it's an unfortunate choice for anything that has to a) perform better than Java is capable of, or b) be packaged in a platform-specific way and shipped to a customer. There are many situations where your application does not require either of these to be true, and you should seriously consider Java for these cases (I've seen some very nice Web pages that used Java to render complex shapes interactively or allow you to tour a data set, and these are wonderful applications of the language; also many in-house tools benefit from server-side or client-side Java Web programming).

      On C++, the language is brilliant and I have nothing but respect for the idea. It's just that C++ presents a great deal of risk to a large development team that can be mitigated by choosing a language better suited to the task (either higher or lower level, depending on what is required).

    14. Re:One Downside by elflord · · Score: 2
      On C++, the language is brilliant and I have nothing but respect for the idea. It's just that C++ presents a great deal of risk to a large development team that can be mitigated by choosing a language better suited to the task (either higher or lower level, depending on what is required).

      The entire problem with your reasoning is that you're mentally hung up on a sort of false dichotomy between "high level" and "low level". What about software that needs to handle matrix operations ? Sure one can implement it in C, but do you want to maintain the end result of such a hairball ? What about software that needs to be able to scale in both directions ? Not only is this idea that all languages "should" be "purely" high level, or "purely" low level wrong, the vast success of C++ is a testimony to this.

    15. Re:One Downside by Anonymous+Brave+Guy · · Score: 2

      Sure, that's a neat example, but the power comes from the handy libwww-perl that slipped in there as much as anything else. You're also doing basic string processing, which is obviously a particular strength of Perl.

      By the same token, using the framework I have available at work, I can (and often do) write a single line of C++ that builds up a structure of labels and data types, uses RPC to have this rendered as a dialog in the client, and fetches back the user-specified values entered into the dialog. If you happen to have the library available, as we both do in our respective examples, you can write very high level code concisely in either language. The fact that many don't do it, particularly in a language like C++, certainly doesn't mean it can't be done.

      Sorry, I'm going to go back and pretend that C++ can approximate the power of a "true" high level language, now. :-)

      --
      If you disagree, post your argument. (-1, Overrated) isn't your personal censorship tool for views you don't like.
    16. Re:One Downside by the+eric+conspiracy · · Score: 2

      Java, like Smalltalk, is a purely OO language.

      That's silly. Sure you may have to use some constructs like Yadda y = new Yadda() once in a while, but the fact is that you can very much write code that nobody would consider OOP in Java. In fact I frequently see such code written by ex C programmers who are in the process of learning Java.

      Key things to watch out for are classes with names starting with Process or ending with Utilities.

    17. Re:One Downside by ajs · · Score: 2
      The entire problem with your reasoning is that you're mentally hung up on a sort of false dichotomy between "high level" and "low level".
      No, I'm not. And sometimes the right tool for the job is both (e.g. a high-level language which uses modules or sub-systems that are written in a low-level language). My concern is that C++ tries to escape the low-level language restraints while not providing the abstraction of a high-level language. The most obvious failing in this respect is memory management, but type management is actually more harmful to maintainability in the large.
      What about software that needs to handle matrix operations ? Sure one can implement it in C, but do you want to maintain the end result of such a hairball?
      Heh. What do you think matrix libraries have been written in for the last 30 years? FORTRAN or C! Yes, there are now C++ alternatives, and some of them are well crafted, but let's not pretend that "back before C++ saved the world" there was no way to do these things cleanly ;-)
      What about software that needs to be able to scale in both directions ? Not only is this idea that all languages "should" be "purely" high level, or "purely" low level wrong, the vast success of C++ is a testimony to this.
      And the vast success of COBOL is testomony to... um... nope, I'm not sure. Adoption of a language proves that the language can be applied to a number of problems. Whether or not it should cannot be ascertained by its adoption. To re-phrase this in terms of pop-culture, we should not assume that the presence of a large fan-base indicates that Brittany Spears is a talented musician whose work is of value to the musical community. :-/
    18. Re:One Downside by ajs · · Score: 2
      Sure, that's a neat example, but the power comes from the handy libwww-perl that slipped in there as much as anything else. You're also doing basic string processing, which is obviously a particular strength of Perl.
      No, actually the major strength of what I pointed out was the homogenous nature of Perl's data types and it's list handling, but the things you point out are very handy as well.

      Other features of truly high-level languages:

      • Dynamic functions and closures
      • The concept of a valid, safe, undefined value
      • First-class collection types that can be manipulated by all language primatives
      • The ability to create large, complex data structures without having to declare their behavior in detail. Rapid prototyping asside (where this sort of thing sets high-level languages in a league of their own), I can't count the number of times I've seen a C++ programmer write page upon page of code that then has to be maintained just to store some intermediate data or organize in the middle of some larger operation.
      • Anonymous data types
      Before you point out that there are times that you want to sacrifice these things for efficiency, let me agree. Yes, you do, and that's what a low-level language is for. At times you use both types of languages at the same time (e.g. PDL is a Perl module that does high-performance binary data manipulation from mathematical transformations to image editing to 3D-rendering... it's mostly written in C and FORTRAN).
      I can (and often do) write a single line of C++ that builds up a structure of labels and data types, uses RPC to have this rendered as a dialog in the client, and fetches back the user-specified values entered into the dialog.
      Cool! That's a handly library to have. Wouldn't it be nice if your language of choice could allow you to use that library and manipulate those objects in a way that was both crash-proof and easily maintained? That would be a high-level language.
    19. Re:One Downside by Anonymous+Brave+Guy · · Score: 2

      Fair enough. I'm really only playing devil's advocate. I wanted to point out that the definition of a "high level" language can't be expressed purely by how much you can achieve with one line in one example. I also wanted to quell the illusion that C++ is a low-level language; while it certainly supports low-level features, you can actually write pretty high-level code with it based on those foundations. Too many people criticise it for being unsafe and low-level, and then go on to advocate languages like Java or C#...

      --
      If you disagree, post your argument. (-1, Overrated) isn't your personal censorship tool for views you don't like.
    20. Re:One Downside by elflord · · Score: 2
      And sometimes the right tool for the job is both (e.g. a high-level language which uses modules or sub-systems that are written in a low-level language).

      Multi language development has problems of its own. For example, implementing objects in C is difficult and error prone. APIs for interpreted languages tend to be dangerous and error prone, especially if you want to develop complete classes in the lower level framework. This is often the case if you want to develop software like GUI toolkits, or anything else that requires objects. The end result is that you're going to have to roll your own ad-hoc object system in the low level language (think GTK), or use a low level object system in some API which forces you to do hideous and unnatural things like manually manipulating reference counts and/or directly manipulating the stack (think implementing objects using the Python API and writing perl modules) Again, this makes C++ a practical solution. C++ is concerned with real world solutions to real world problems, not the appeasement of language masturbators.

      Heh. What do you think matrix libraries have been written in for the last 30 years? FORTRAN or C! Yes, there are now C++ alternatives, and some of them are well crafted, but let's not pretend that "back before C++ saved the world" there was no way to do these things cleanly ;-)

      Take a look at those C and fortran implementations. The vast majority of the ones I have seen are positively hideous. In particular, a number of the fortran ones are GOTO-laden spaghetti. Take a look at the NR code for a hideous mess in C. Of course it could be done, but the result was an unmaintainable mess.

      And the vast success of COBOL is testomony to... um... nope, I'm not sure.

      Then perhaps you need to think more deeply. There are always good reasons why a technology succeeds. Beauty and purity are not as important as you think they are. At least two good reasons I can think of are standardisation (how many standard languages were there in 1968 ?) and vendor support, in the sense that good implementations are available (which had a lot to do with standardisation)

      Adoption of a language proves that the language can be applied to a number of problems. Whether or not it should cannot be ascertained by its adoption.

      That it can be applied to a lot of problems is not sufficient in itself. There are numerous other factors. Suffice it to say that abstract notions concepts of "truth", "beauty" and "purity" are not great reasons for adopting a language.

    21. Re:One Downside by Unknown+Lamer · · Score: 2

      Java has only some of C's problems while being totally platform-antisocial (platform neutral would imply that it plays nicely with all platforms which is patently untrue). I will say that Java has one of the best object models of any language out there, but 1) that will change when Perl6 hits the streets and 2) it's somewhat overshadowed by the failure of the Java libraries to live up to the promise.

      Umm, CLOS...

      --

      HAL 7000, fewer features than the HAL 9000, but just as homicidal!
    22. Re:One Downside by Talonius · · Score: 2

      Old post but I admire anyone who can say they're wrong. :)

      On the plus side his post was informative to me. While I'm familiar with Interfaces I'm still fumbling about with the number of objects that MS has made available inside the .Net framework.

      There literally is one for taking out the garbage.

      .:|T

      --
      My reality check bounced.
  2. buggy implementations. by rebelcool · · Score: 2
    all the various implementations of the STL i've used have had different bugs in them. Granted, you need to be doing some pretty advanced things with it, but thats what its there for.

    And have you seen the actual code for the STL? Ugh. It demonstrates just how bad and obscure C++ syntax can be.

    --

    -

  3. AFAICT, Very Little by 4of12 · · Score: 2

    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."
  4. STL downsides by Hawke · · Score: 4, Interesting
    The header files you want to read to find out the API's are practically illegable. You'll probally want to get a book or other such better documentation.

    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.

    1. Re:STL downsides by joshwalker · · Score: 2, Informative

      Don't read headers to learn STL. Get a good book like Nicolai Josuttis's _The_C++_Standard_Library or visit SGI's STL Site

      Don't inherit from an STL container. They are not designed for inheritance (no virtual destructors). Instead, keep your current model and prefer aggregation.

    2. Re:STL downsides by Tattva · · Score: 2
      Don't read headers to learn STL. Get a good book like [...]

      I like "STL Tutorial and Reference Guide" by Musser and Saini (Addison-Wesley Professional series, aka. The Swoosh books). Yes, the online guide is also very handy.

      Don't inherit from an STL container. [...]

      Thought I already said that.... *shrug*

      You probably already know this, but in general, you can rule out extending any class that does not have a virtual destructor. This is true for two reasons: destroying a reference to the base class will not call your inherited destructor and secondly failing to declare a virtual destructor is a widely accepted C++ declaration style to indicate the class should not be inherited since there is no "sealed" or whatever in C++.

      --
      personal attacks hurt, especially when deserved
    3. Re:STL downsides by ncc74656 · · Score: 2
      That said, I like STL and highly suggest using it. Never write a linked-list again.

      It was good for fleshing out the first version of an image compressor that needed to maintain a few linked lists as part of its operation. One of the first optimizations I ended up making, though, was to rip out the STL linked lists and do old-school C-style linked lists instead. The speed improvement was non-trivial. (I also threw a wrapper around malloc() to minimize the number of calls to the real malloc()...that probably yielded the biggest speed boost, and it wouldn't have been possible with STL.)

      --
      20 January 2017: the End of an Error.
    4. Re:STL downsides by ComputerSlicer23 · · Score: 2, Interesting
      Yes it is, in fact it is a commonly known optimization to override an allocator. Lots of written material mentions it if you take the time to readup on it. Write a custom allocator, you know the third option to all of the STL containers? Bjarne in fact says that is the whole reason why it was added was specifically so people could get very fine control over memory allocation. Nearly everything about the STL and all of the templated types in C++ is to give you completely control over the performance/size parameters of the code. Bjarne knew nobody would use it otherwise.

      They got control to control both placement and the memory allocation routines. The default allocation calls malloc, writing your own can commonly speed up code an order of magnitude.

      That was in Design and Evolution of C++, if you want to know how to write an allocation check out boost.org, and Jossutis's book. Several people linked to the book above.

      <flame> Remember: Just because you didn't know how to do it doesn't make it impossible. </flame>

      Sorry about the flame, but people who don't know enough about C++ and then say it is fundamentally flawed in ways that it was specifically designed to accomadate aggrevate me very much. It isn't you're particular situation (heck you might have done this before allocators got standardized). Just so many people are ignorant of the facts and then blame C++ because it does the right thing 95% of the time and gives them control of the other 5% to override it.

      And yes I own a copy of the ISO C++ standard. I am that much of a C++ geek.

    5. Re:STL downsides by stripes · · Score: 2
      I like "STL Tutorial and Reference Guide" by Musser and Saini (Addison-Wesley Professional series, aka. The Swoosh books). Yes, the online guide is also very handy.

      That one is nice because it has a lot of short examples. The Josuttis book has a lot more detail on many things (plus covers non-STL topics). Get both. Read the swoosh book first.

    6. Re:STL downsides by leviramsey · · Score: 2

      Mandrake is expecting to move to gcc3 for Mandrake 9.0 (I doubt it will be called 8.3). As a matter of fact, they've begun the process of building things with gcc3.

      Admittedly, since the ABI is changed, you may have difficulty using g++3 for some time.

    7. Re:STL downsides by God!+Awful · · Score: 2


      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.

      Classes derived from containers are great. I use them all the time. Sometimes, I inherit them as public and sometimes as protected. It depends on the situation.

      -a

  5. Not supported in C++.Net (??) by Ars-Fartsica · · Score: 2
    Maybe someone can confirm this, but the latest .Net SDK does not seem to provide support for the STL.

    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.

    1. Re:Not supported in C++.Net (??) by Tattva · · Score: 2
      Templates are not supported when targetting the CLR - target Win32 and you'll be just fine. If you're targetting the CLR - you not only lose templates, but also multiple inheritance. You effectively get a subset of C++.. (so much for M$'s claim of language independence for the CLR.. hehehehe)

      Word on the grapevine is that generics is a possible future extension of the CLR and C#.

      I can only pray this is the case, I have spent a lot of time getting good at the C++ Standard Library and the STL, and I now have a warm place in my heart for the amazing, frustrating, elegant beast. Until generic programming is available in C#, it will definitely be a mixed bag for me.

      --
      personal attacks hurt, especially when deserved
    2. Re:Not supported in C++.Net (??) by mmacdona86 · · Score: 2

      The point is that the CLR is not all that language independent if it can't support important language features like generics and multiple inheritance. AFAICT, the big stumbling block for really supporting C++ is multiple inheritance. Generics may get shoehorned in to the CLR, similarly to how they are being added to Java with 1.4.

    3. Re:Not supported in C++.Net (??) by mmacdona86 · · Score: 2

      If you are going to say that it doesn't matter what language features are supported by a platform, than the Java VM is just as language-independent as the CLR. Multiple languages target it--and the Python implementation is in widespread use.

      In reality, both the CLR and the Java VM favor particular styles of languages--and have limitations that make standards-conforming implementations of other languages quite difficult. Calling them language independent, is, to that extent, a myth.

  6. Re:Lots of overhead. by nonya · · Score: 4, Informative

    Um...you don't know what you're talking about. The STL does not make use of virtual functions.

  7. Not all compilers support it, god-awful comp errs by Avumede · · Score: 5, Informative

    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.

  8. Not many by Xentax · · Score: 5, Informative

    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.
    1. Re:Not many by Xentax · · Score: 5, Informative

      Oh, one other thing:

      Pay attention to which operations are expensive for the various data structures (map vs. list vs. vector, etc.).

      The fact that the operations' syntax for each of these is standardized is a double edged sword -- it makes for clean code and syntax, but it can mask poor-performing operations. Consider iterating over a map vs. over a list, for example.

      So, consider carefully what operations you perform on various structures, and (of course), profile where/when appropriate. Looking at the actual implementation of the STL you choose can go a long way in revealing such troublespots, if that's an option (SGI's implementation is pretty easy to get ahold of).

      Xentax

      --
      You shouldn't verb words.
    2. Re:Not many by jkujawa · · Score: 3, Insightful
      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.
      SGI's STL documentation is excellent. I always have a browser window open to it while I'm coding. And, as it's the basis of the STL in g++'s libstdc++, it's quite accurate. SGI's STL is actually used by a number of platforms, and works pretty well.

      One think to watch out for is that the string class isn't thread-safe under linux.

      http://www.sgi.com/tech/stl/

      I also recommend Scot Meyers' "Effective STL".
    3. Re:Not many by wurp · · Score: 2

      STL's performance is fantastic! PhDs have optimized the hell out of the algorithms, and with template and inline functions (and no virtual functions), often all of the overhead of even the function calls will be compiled away, leaving pure screaming op-codes after compilation is done. This tendency to expand calls out into their op-codes instead of using calls to functions is responsible for much of the code bloat that comes with templates.

    4. Re:Not many by Xentax · · Score: 2

      String isn't threadsafe in Solaris either; I believe that's actually SGI's implementation.

      It was lucky for us that we'd already been using ACE, since ACE's CString IS threadsafe.

      ACE was great for threading -- Solaris doesn't support the r-w mutex (though POSIX on Solaris does), but we were better off once we set to working around that.

      Xentax

      --
      You shouldn't verb words.
    5. Re:Not many by irix · · Score: 2

      Not to "me too!" this thread, but I also program with the STL on Solaris, and I find it excellent.

      I own the STL Tutorial and Reference Guide and Effective STL.

      On the web, I use the SGI docs and also the Rogue Wave Docs since the Solaris STL is from Rogue Wave. I find them both adequate for 99% of the programming that I do. The one thing to note on Solaris is that the STL is missing a hash map. The hashmap is technically not part of the STL spec yet, but it most likely will be for the next iteration, and the stlport implementation has one available.

      Several people have mentioned one of the downsides being unintelligible error messages. This is true, but I think that (on Solaris anyways) error messages coming from templated code generally suck.

      --

      Do you even know anything about perl? -- AC Replying to Tom Christiansen post.
    6. Re:Not many by irix · · Score: 2

      The ACE reference material is good, but what is hard to come by is good (and up-to-date) examples.

      I bought Dr. Schmidt's first ACE book when it came out a few months ago, and I'll be buying the next one when it comes out. It is full of good examples.

      --

      Do you even know anything about perl? -- AC Replying to Tom Christiansen post.
    7. Re:Not many by sir99 · · Score: 2
      Pay attention to which operations are expensive for the various data structures (map vs. list vs. vector, etc.).
      How very true. I had a class which contained a std::map of shared variables which are iterated over a rediculous number of times, for use in Affine Arithmetic. After profiling, I saw that the program spent most of its time iterating over the map, and the rest of the time deleting elements from it!

      After I changed the map to a wrapper for std::list, performance increased by about 130%. Once I thought about it, a list made much more sense, since I was iterating over it, never doing random access.

      --
      The ocean parts and the meteors come down
      Laid out in amber, baby.
  9. Well.. by DCram · · Score: 2, Informative

    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.
    1. Re:Well.. by PD · · Score: 2

      Don't do this! Every STL programmer knows the idiom string foo="";

      If you #define NULLSTR "" somewhere in a header, you just waste someone's time when they have to go look up what it is. There's absolutely no reason to make that definition. Reminds of the time I saw code where someone had

      #define ONE 1
      #define TWO 2
      #define THREE 3

      etc. There's no point in it other than obfuscation.

    2. Re:Well.. by DCram · · Score: 2, Interesting

      Laugh..every reply is a good one. And one that I know already. I said it was sumthing stupid that I do not that I didnt know it was stupid :)

      actually I dont create the NULLSTR = ""; very often. Here at work one of the "managers" thought it read better so we use it. Code review goes easier when you dont have to fight the same pitched battle every time.

      --
      If I were only smart enough to accomplish the things I dream about.. Or maybe too dumb to care.
    3. Re:Well.. by joto · · Score: 2

      Well, if NULL is not 0, then it is ((void *)0). Otherwise, it's just not C. (Well, it can also be defined in some compiler-specific way, but when you cast NULL to a long, it should have numeric value 0).

    4. Re:Well.. by joto · · Score: 2
      Yup, you are right, and I remembered wrong.

      It's the source code representation of C and C++ that guarantees that a 0 in the source code will be read as a pointer literal of the appropriate type instead of as a literal integer. The actual representation of that literal is machine specific (but could be a word-sized bitstring of zeros, as is quite common).

      The reason "#define NULL ((void*)0)" is popular in C is because it helps detect stylistic misuse of NULL, since NULL is intended to represent a null pointer. It also makes it clear in some contexts (such as varargs functions, and old-style functions without a prototype) that a pointer value is intended, and not an integer.

      The reason that doesn't work in C++ is because C++ has a different type-system. In C, one can convert freely both ways between any pointer type and "void*", without a cast. In C++ one needs a cast to convert from "void*". Thus "((void*)0)" defeats it's own purpose there, since anywhere you used it, you would require an explicit cast back to the pointer type you intended, so a literal "0" would have been easier, and by continuing to use the NULL macro, you make your own life a lot harder.

      So, with these rules "double *foo = (void*) 0" is not valid C++, and the compiler should reject it. But "double *foo = (double*) (void*) 0" is valid. Now, I've been playing games with casts, and that is what would be happening if you defined NULL as "((void*)0)", and initialized it with "double *foo = (double*) NULL".

      It is possible that the C++ standard allows an implementation to fuck up in this case, but an implementation that didn't recognize "(double*)(void*)0" as a literal pointer to null would be very strange (even among those extremely rare and weird compilers having different pointer representations for different pointer types, non-zero nullpointer representations, and different nullpointer representations for different types).

  10. STL downsides by Todd+Knarr · · Score: 2

    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.

  11. Re:Lots of overhead. by Anonymous Coward · · Score: 2, Informative

    What are you talking about? The STL uses templates for genericity, not virtual functions. And no, there isn't a lot of overhead when you use the STL if you watch the things you're doing. Any overhead incurred by virtual functions (and it's typically dwarfed by whatever you do inside the functions called) is predictable, and shouldn't cause "havok" on your real-time requirements. Admit it, you're talking out of your ass.

  12. Re:What virtual functions? by billnapier · · Score: 4, Informative

    But templates increase code size as the compiler has to genarate a different version of the class for each unique instance that you use.

    ie. If you use a Vector to hold 15 different things, the compiler has to generate 15 different version of the Vector class to compile your project.

    May not be that much of a problem if you've got the memory.

  13. Re:Lots of overhead. by Slowping · · Score: 2, Insightful

    Too bad I don't currently have any moderator points, but I agree with this statement.

    It really helps to pre-plan what you're going to do with the STL (I guess that goes with everything else in software dev). It can get really ugly if you use them on-the-spot as you hack away at an implementation. But if you think it through, you can control the costs of using the STL. Pre-plan and take advantage of C++'s "pay only if you use it" philosophy.

    --
    (\(\
    (^.^)
    (")")
    *beware the cute-bunny virus
  14. Re:Lots of overhead. by emount · · Score: 5, Informative

    The C++ language spec explicitly specifies the performance requirements for STL components (which is rare in a language spec, IMO)... the brunt of the work is at compile time, and there is no virtual function dispatching in the STL.

  15. the STL is imporperly named by dutky · · Score: 4, Insightful
    The biggest downside of the Standard Template Library is that it isn't very standard. The support for templating, across a range of compilers, just isn't very consistant, which makes using the STL in a portable manner almost impossible. Aside from that, the STL is, to my mind, just another giant complex wart on top the mind-numbing complexity that is ANSI C++ itself.

    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.

    1. Re:the STL is imporperly named by MobyDisk · · Score: 2

      You point out that STL has support issues, but you place the blame in the wrong place. The fault is poor compilers, not a poor standard.

      If my web browser does not implement cookies, is HTTP no longer a standard? STL is a standard, and if a vendor chooses not to conform, that is not the fault of the standard.

    2. Re:the STL is imporperly named by ivan256 · · Score: 5, Insightful

      As with OOP itself, generic programming is a Really Good Idea(TM)

      Be careful. It's generalizations like this that end up in the hands of managers and can lead to Really Bad Software(TM). There are plenty of cases where a small generalized solution is more apropriate. THere is no golden paradigm for software development.

    3. Re:the STL is imporperly named by SLOGEN · · Score: 5, Informative

      > The biggest downside of the Standard Template
      > Library is that it isn't very standard.

      No, but the C++ Standard Library is in ISO14882 ("Programming Languages -- C++"), and it "superceeds" and embraces the old STL. Unfortunatly most people (and tutorials) still refer to either the STL definitions or use the term STL about the standard library.

      > The support for templating, across a range of
      > compilers, just isn't very consistant, which
      > makes using the STL in a portable manner
      > almost impossible.

      Depends on what you use. Normally, it's not the containers themselves. that makes trouble, it's the functors and the algorithmic versions of operators (i.e. std::less and such), which most programmers don't use for the first few months.

      BTW: GCC-3 has EXCELLENT template-YOUR_FEATURE_HERE support as well as standard library support.

      > Aside from that, the STL is, to my mind, just
      > another giant complex wart on top the
      > mind-numbing complexity that is ANSI C++ itself.

      C++ is complex because of the possibilities it offers... well, and it's heritage. To the untrained even the simplest tasks are compilcated... think how long it took to understand (not just learn) multiplication :)

      > As with OOP itself, generic programming is a

      Hmmm.... I consider generic programming perpendicular to OOP (this is a nice analogy when explaining why using GP from OOP sometimes requires "multi-dimensional" programming... if you understand?)

      > Really Good Idea(TM) but its implementation in
      > C++leave something to be desired for simplicity
      > ans accessability.

      Agreed, as well as consistence in compile-time versus runtime versions of syntax.

      > 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.

      The Standard library (not STL) is the best thing that happened to C++ for years. I doubt it could have been done cleaner and more flexible in C++?

      I would like to see optional garbage collection (with fitting restrictions to legal programs) introduced into C++. That's the no. 1 thing holding back (advanced/modern) OOP in C++.

      --
      Helge

      --
      SLOGEN [ http://ungdomshus.nu : Sebastian cover music]
    4. Re:the STL is imporperly named by tommck · · Score: 2
      ...support for templating, across a range of compilers, just isn't very consistant...

      How is this insightful?
      Just because compiler vendors don't implement the standard properly, this is the fault of the C++ language (of which STL is part)??
      That's some pretty broken logic there.

      ...the STL is, to my mind, just another giant complex wart on top the mind-numbing complexity that is ANSI C++ itself...

      This is just blindingly insightful too!
      This is a flame without even pitching an alternative that solves the supposed problems with STL.

      T

      --
      ---- It puts the lotion on its skin or else it gets the hose again. It does this whenever it's told.
    5. Re:the STL is imporperly named by MobyDisk · · Score: 2

      1) I've never exceeded STL's requirements (without having the requirements too specific to expect any library do what I need). I'm curious what it does not do that you want, and how you chose to work around it.

      3) Agreed! But please tell me how STL could have been designed to have better error messages?

    6. Re:the STL is imporperly named by Tattva · · Score: 2
      Also, try reading a compiler error that mentions an std::<vector<std::string > > std::string itself expands to std::basic_string<yadda yadda yadda>. I'm sure there was a good reason for it, but I'll be darned if I can figure it out.
      IMO, string is just a special case of container. Since there are multiple types of elements commonly used in strings, (different character encodings, Unicode vs Multibyte, etc) they did what they did for vectors and templatized on the element type. They also templatized the memory management scheme to allow allocation performance enhancements since allocation is/can be one of the most-expensive-most-commonly-used operations in C++. If they didn't templatize it they would have had to have multiple separate implementations for each character encoding and memory management paradigm. Since there are only 3 numbers in CS, zero, one, and many, this would have been anethema to the STL designers.

      --
      personal attacks hurt, especially when deserved
    7. Re:the STL is imporperly named by realdpk · · Score: 2

      If all the standards are different, it might not be worth the time to look in to it at all. It doesn't matter what is at fault, it's all about practicality.

    8. Re:the STL is imporperly named by tommck · · Score: 2

      The standards are not different. There is ONE standard. If you do not like the STL implementation or the compiler's template support on your platform, change. That has nothing to do with the STL. That's like saying Java sucks because Microsoft's JVM stopped at JDK 1.1.4 support!

      --
      ---- It puts the lotion on its skin or else it gets the hose again. It does this whenever it's told.
    9. Re:the STL is imporperly named by Joe+Rumsey · · Score: 2

      Pfft, it doesn't matter what phrases happen to stick in managers' heads. Let's say my manager happened to overhear me saying "As with OOP itself, Generic Programming is a Really Good Idea."

      Then later on, when he asks me what I'm doing and I don't really feel like explaining it, I can just say, "I'm doing some Generic Programming, it should be even better than the OOP version!" and he will leave me alone, because I've already taught him that Generic Programming is a Really Good Idea.

      Then later you can mention that, for example, revectoring structural pathways is important for optimal performance, because you never know when you'll need the next excuse to work on important stuff in peace and quiet.

  16. Re:Lots of overhead. by PD · · Score: 3, Informative

    Just to add to the parent... That's right. STL does not use virtual functions. In fact, STL is not an object oriented library at all. It's generic programming, and it's the coolest thing that I have seen for C++ ever. (Now is the place where LISP programmers can shout out that they've been generic for 40 years.)

  17. Re:Lots of overhead. by tenman · · Score: 4, Insightful

    If your building an application, then you will not want to use STL. STL is a speed deamon. It will be great for coders that write to hardware (ex: phone switches, automotive computers, etc...). Templates is the name of the game here, and because of the lack of objects, the programmer enjoys the power of C++, and the speed of the older style ANSI C compilers.

  18. Re:Lots of overhead. by Hawke · · Score: 2, Interesting
    there is a lot of overhead with using the STL. Virtual function and things of that like can make your code bigger and slower.

    STL doesn't normally use virtual functions, unless some of the comparison functions or functor objects do. The main cause of bloat (in my experience) is the lack of provided specializations, and the huge symbol names generated by name mangling.

    (Fer fun, create a map< foo, map<bar, map<fred, qux> > >, and run "nm" on the generated .o file. I had a problem with blowing up the size limits on the default Solaris linker with stunts like that)

  19. Not many drawbacks by emarkp · · Score: 5, Interesting
    I've been happily using STL for about 3 years now. The biggest drawbacks (IMO) are:
    • Kitchen sink syndrome: There are a lot of features in STL, and to use some of them you need functors, etc. Sometimes it's just easier to read if you use a normal for loop instead of using for_each, etc.
    • verbose type syntax: When you use the containers, like (say) std::vector, you have to declare your iterators as:
      std::vector<int>::iterator i;
      If you change to a std::list container, you'll have to change your declarations. Of course, you can mitigate that by using typedefs, and then you only have to change the typedef, but it can still get a bit wordy.
    • unexpected results: Understand the difference between remove() and erase() in the containers.

    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.

    1. Re:Not many drawbacks by lkaos · · Score: 2

      # verbose type syntax: When you use the containers, like (say) std::vector, you have to declare your iterators as:

      std::vector::iterator i;

      Of course, this is a bit exaggerated. If your using STL frequently, then you can just use a:

      using namespace std;

      And typedefs should definitely be used not just to save typing but to allow different containers to be used without massive search-and-replace. I would argue that this is a feature if anything.

      --
      int func(int a);
      func((b += 3, b));
    2. Re:Not many drawbacks by 4of12 · · Score: 2

      Of course, this is a bit exaggerated. If your using STL frequently, then you can just use a:

      using namespace std;

      I used to do that nice trick of cleaning up horrible punctuation until higher C++ gurus told me that using all of the std namespace would bloat my code unnecessarily.

      Should I have argued with "Only import what you really need to use."?

      --
      "Provided by the management for your protection."
    3. Re:Not many drawbacks by tardibear · · Score: 2, Interesting

      higher C++ gurus told me that using all of the std namespace would bloat my code unnecessarily

      Get new gurus. Putting using namespace std; into your program (especially in a header file) is regarded by some as poor style but it certainly won't "bloat your code".


    4. Re:Not many drawbacks by Jeremy+Erwin · · Score: 2
      using namespace std;
      can cause namespace collisions. But you can import the needed class individually:
      using std::vector;
      .
    5. Re:Not many drawbacks by freuddot · · Score: 2, Insightful


      verbose type syntax: When you use the containers,
      like (say) std::vector, you have to declare your iterators as:

      std::vector<int>::iterator i;

      If you change to a std::list container, you'll have to change your declarations. Of course, you can mitigate that by using typedefs, and then you only have to change the typedef, but it can still get a bit wordy.


      No !

      Never ever directly declare your iterator like that. Instead, use :

      class A
      {
      public:
      typedef vector<int> IntContainer;
      IntContainer mContainer;
      void f();
      };

      then, use :

      A::f()
      {
      IntContainer::iterator it;
      }

      instead of :

      A::f()
      {
      vector<int>::iterator it;
      }

      Magically, now you can go from a vector to a list, without chaning all your iterators declarations.

    6. Re:Not many drawbacks by lkaos · · Score: 2

      Get new gurus.

      Agreed. The using directive is simply a directive that tells the compiler to import all the names from std.

      It's equivalent to the import directive in java. As far as I'm concerned, the only time that using shouldn't be used to import the std namespace is when a conflict is likely to occur (most environments have coding standards making collision almost impossible).

      --
      int func(int a);
      func((b += 3, b));
    7. Re:Not many drawbacks by Viking+Coder · · Score: 4, Funny

      #define private public

      The one macro you'll ever need. Heh.

      --
      Education is the silver bullet.
    8. Re:Not many drawbacks by Paul+Komarek · · Score: 2

      Two questions for you:
      1) Are you Mark Lutz?
      2) Are you a Python programmer?

      This isn't a flame. I love Python. I ask because the only other place I've seen this macro is in Mark Lutz' Python books (published by O'Reilly). However, I don't use C++ regularly, and wouldn't know if this was a common idiom.

      -Paul Komarek

    9. Re:Not many drawbacks by Viking+Coder · · Score: 2

      I think I saw it in a Mark Lutz book. I shuddered in pain and horror, when I first saw it. =)

      You're right, I should have given credit where credit (or blame?) is due.

      --
      Education is the silver bullet.
    10. Re:Not many drawbacks by Paul+Komarek · · Score: 2

      As a (primarily) C programmer, I saw this macro as a way to smack down those misguided C++ pedants. ;-)

      -Paul Komarek

    11. Re:Not many drawbacks by Jeremy+Erwin · · Score: 2

      Uh no...

      I'll give you an example. A programmer is developing a linear algebra application and designs a class to handle vectors-- the mathematical kind, not the STL kind.

      If the programmer uses namespaces intelligently, he can place his vector class in a custom namespace. (e.g. linalg). Thus std::vector<double> and linalg::vector<double> will be recognized as separate entities-- each with distinctive behavior.

      You may ask-- why doesn't the programmer use the name linalg_vector<double> instead? Not every potential namespace collision is avoidable. I might want to link my linear algebra program with a plotting/image processing library. It would be a lot more useful to me if their functions/classes were segregated into namespace plot-- so that I didnt have to make sure that my fft functions (linalg::fft) didn't conflict with their fft function (plot::fft).

    12. Re:Not many drawbacks by Paul+Komarek · · Score: 2

      Is it allowed to do something like

      #define undef #define HAHAHA \/\/

      ;-)

      -Paul Komarek

  20. Re:Lots of overhead. by billnapier · · Score: 2, Informative

    I'll admit that I may have spoken rashly about the virtual functions, but my other points about templates and code bloat still hold true.

    And it will cause havok if you're not aware of it.

  21. Rimshot emoticon by geophile · · Score: 2

    Here it is, an ASCII rimshot:


    \/!


    This is my invention, which is mine.

  22. Cross-platform compatibility is a pain by catslaugh · · Score: 4, Informative
    The STL is very effective. Most of the problems I've had with it involved cross-platform compatibility (as I tend to develop code that has to run on a variety of platforms). Depending on your various STL versions and compiler versions, you can have to deal with the vagaries of the presence or lack thereof of namespaces, the availability of default template arguments (which has led me to typedefs like typedef map<RWCString, RWCString, less<RWCString>, allocator> NVPairMap;), and some real headaches figuring out how to get the #includes just right to deal with the way that Microsoft has two different versions of the iostream headers in MSVC.

    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."
    1. Re:Cross-platform compatibility is a pain by MobyDisk · · Score: 2

      STL works in GCC.
      GCC is cross platform.
      Therefore, STL is cross platform.

      Seriously, I've ported utilities and 3D games across multiple OSs, and STL is the portion I have the LEAST trouble with.

  23. Check out "Effective STL" by Myers by lkaos · · Score: 5, Informative

    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));
    1. Re:Check out "Effective STL" by Myers by jkujawa · · Score: 3, Insightful

      I believe what you mean is never use vector, which breaks certain semantics.
      vector is the most useful container in the STL, and is the basis for the STL string class.

    2. Re:Check out "Effective STL" by Myers by joshwalker · · Score: 2, Informative

      I think the parent meant never use vector

      vector itself is very useful as a container, as well as for using C interfaces; since the storage is guaranteed to be contiguous (at least in the technical corrigendum), you can do things like:

      vector<char> buffer(100);
      readSomeData(&buffer[0], 100);

    3. Re:Check out "Effective STL" by Myers by jkujawa · · Score: 2

      I misspoke. vector is the boogeyman.

    4. Re:Check out "Effective STL" by Myers by MobyDisk · · Score: 2

      What is wrong with vector ?

    5. Re:Check out "Effective STL" by Myers by Tattva · · Score: 2
      vector itself is very useful as a container, as well as for using C interfaces; since the storage is guaranteed to be contiguous (at least in the technical corrigendum), you can do things like:

      vector<char> buffer(100);
      readSomeData(&buffer[0], 100);

      In fact, it is the only legal way in the C++ Standard Library (and the STL) to pass a non-const STL-controlled memory data segment to legacy functions (such as library API's like Win32.) IIRC they do not make the same promise about basic_string. Also, auto_ptr does a "delete _ptr", not a "delete[] _ptr" so you can't use it for C arrays. This means that the only valid way to get a non-const pointer to STL-managed raw memory that is safe is to dereference a reference like that one above or "begin()", etc. The funny thing is that the contiguity guarantee in the specification only came about recently, it wasn't in the original spec, but I think that it was an assumption from the beginnning.

      --
      personal attacks hurt, especially when deserved
    6. Re:Check out "Effective STL" by Myers by lkaos · · Score: 3, Informative

      Quick summary of the story.

      The C++ commitee thought that a proxy class could be used to emulate a primative data type. They didn't know how to do this, but they believed someone would figure it out. To encourage this, they forced vector<bool> to be specialized to return a proxy object and to store the bits internally as a bitset (which is more efficent since it uses 1 bit per element instead of 1 byte).

      Problem is that proxy classes cannot emulate primative types and the experiment failed. As it is, the vector bool class is still part of the standard and currently violates the rules for the behavior of a container class. (Namely that &v[0] is invalid).

      Failed experiment that somehow made its way into the standard.

      --
      int func(int a);
      func((b += 3, b));
  24. Where the linkage? :-( by NOT-2-QUICK · · Score: 2, Informative

    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
  25. Partial List by Viking+Coder · · Score: 5, Informative

    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.
    1. Re:Partial List by randombit · · Score: 2

      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.

      I agree, it is missing some stuff. But I suppose it depends on what you're used to. I would much rather use std::string than the C str* functions, and I've never felt particularly constrained by the string API. It's one of those YMMV things, I guess. Personally, I like the simplicity, and I've never run into a problem with anything that couldn't be done easily with std::string and the generic algorithms.

      But OTOH if you want to do your own string class that's a Has-A of std::string, go for it. C++ is all about reuse, after all. :)

      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.

      So, always use iterators. That's what they're there for, after all. The operator[] access operations are useful, and I use them a lot with vectors and maps, but all of the generic algorithms use only the core container API and work great.

      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.

      Agreed.

    2. Re:Partial List by garett_spencley · · Score: 2

      If you can't afford a stack push, then you probably shouldn't be using STL in the first place.

      I disagree.

      IMO when deciding wether or not to use the STL (or deciding wether or not to use C++ instead of C) you have to make a very big compromose: performance vs. nice code.

      Nice code is essential to a stable program and IMO the STL is perfect for this. It adds stability and makes coding things like hash tables, trivial string operations, vectors etc. a breaze. However, this all comes with a performance hit.

      Lets say I decide to use the STL in my application because while it must be as fast as possible I'm going to sacrifice some performance for stability. I'm not going to sacrifice more by wrapping it with an API. That's stupid.

      So why would you do it? Because not all your developers like the STL? That's even stupider. If I'm going to have other developers working on my application that makes use of the STL then they must know the STL. Why would I expect anything different?

      It's not like I'm going to say "Oh you don't know perl? That's okay I've written a compiler that will allow you to write your code in C and output a perl script."

      It just doesn't make any sense.

      The only acceptable times to use a wrapper IMO is for portability or when you want to take a number of related API's and merge them into one easy to use API for your developers. Wrapping the STL because your programmers don't like it just seems like a terrible waste of performance to me. I've already sacrificed all the stack pushes I'm willing to just to be able to use the STL. I'm not willing to sacrifice more because I have programmers who don't like the API I've chosen.

      --
      Garett

    3. Re:Partial List by Viking+Coder · · Score: 3, Interesting

      My assertion is that people change their mind. If you have an API that you can live with, you can always change your mind as to how the back-end works, and all you have to change (hopefully!) is the class that you're working on. Encapsulation is your friend.

      Also, I hate that people will free-form type functors, in the middle of their code. People end up with multiple functors that all do the same thing. The "method" paradigm is far better, that the algorithm and data are coupled. It makes it far easier to organize your code, far easier to make global changes and manage your code, and reduce bugs!

      If you didn't wrap the str* functions in a class, then it cost you a lot of effort to switch your code to std::string. If you DID wrap the str* functions in a class, it was probably pretty painless. (Other than something like sprintf - a major pain in the butt to get working in STL, in my opinion.) I don't think it's responsible to think that you'll ALWAYS code in STL, from now until the end of time. Didn't you think that, at one point, about the str* functions?

      Another thing I dislike - many, many languages support OO methodoligy, which makes porting code from one language to another pretty easy. Templates are not easy to port to another language. And they really don't buy you that much, in your end-user code. They're great for quickly developing something, and potentially making it more portable, but if you encapsulate all of the functions (ie METHODS), you can always change your mind, and your client code becomes more portable, too. (As in, porting to another language, if you need to.)

      It's always easier to make a change in one place than in a thousand places. Encapsulation makes that possible - but unfortunately the only way to encapsulate something is to wrap it in another API.

      I'm not proposing to wrap it because your developers don't like it. Of course they should know it, and they should like the good parts, too. But having everyone re-invent the way to do case-insensitive comparisons is insane. Those kinds of decisions should be encapsulated in one location. If you know a better way than writing an API wrapper, I'd love to hear about it.

      And I'm not saying you should make myVector<myString>, I'm talking more about things like myStringVector. Application data should not DEPEND on the STL for its interface. Just because the STL is a useful API, don't think it's the Holy Grail. Too many people just LOVE to code Is-A relationships, when a Has-A relationship is better in every measurable sense.

      That's my argument. I could be wrong. =)

      --
      Education is the silver bullet.
    4. Re:Partial List by elflord · · Score: 2
      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.

      I agree, but it's not part of STL.

      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.

      This is terrible advice. std::string already has way too many member functions as it is-- and you want to tack on more ??? The main problems with string is that it includes functionality that really should exist in the generic algorithms, and the ambiguity re: whether or not string is reference counted is problematic.

      The best way to extend string is to write algorithms or non-member functions. The existing member functions provide more than enough functionality.

      Also, I hate that Containers change paradigms on you, some places you can use integer indecies,

      You can't treat something that isn't random access as though it is. It's quite simple. BTW, the simplest way to get consistency is to use iterators all the time.

      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.

      No. You can remove elements from a vector. Use erase(). The point is that there are generic algorithms. There are only special member functions in cases where a specific implementation for that container is more efficient than a naive iterator based implementation. For example, the list class can remove elements more efficiently, so it provides a special method for it. OTOH, the best one can hope for in a vector is the performance offered by the generic version, so no special member function is provided.

      As a general rule, adding member functions is bad, because member functions are more tightly coupled to a class than non-member functions. This is why STL includes a lot of non-member functions. When you find that a container lacks a member function you want, always check to see that there's a generic lowest common denominator non-member. There usually is. Cheers,

    5. Re:Partial List by Viking+Coder · · Score: 2

      vector::erase doesn't take an integer index, it takes an iterator. Granted you can do math on the iterator, but it makes for long and ugly one-liners to have to refer to your container multiple times on one line. Same thing with vector::insert.

      string::insert - if you want to insert one character, or a repeating block of a character, also takes an iterator. string::erase also takes an iterator, to erase one character.

      I suppose I should have been more clear and indicated that the methods on the container switched paradigms in a way that I don't like, not the actual containers themselves. Unfortunately, the compiler is not always effective at noticing the difference between an iterator and an integer. My first foray into this was to try to erase the first character in a string. I sent 0 to string::erase, with decidedly unsavory results. Of course, it was my mistake - I should have known the methods better, before attempting to use them - but I tend to find that the most obvious way to use a function should be the way a function actually works, unless there's a good reason it shouldn't. And like I said, unfortunately, compilers (both MSVC++6 and Intel 5.0?) aren't very good at protecting you from making mistakes - because 0 is both a pointer and an integer, for instance. *shrug*

      --
      Education is the silver bullet.
    6. Re:Partial List by Viking+Coder · · Score: 2

      I agree, but it's not part of STL.

      std::string, just like std::vector. Those seem homogenous to me. When I bought the book "Effective STL" by Scott Meyers, there's documentation in there on std::string. There's also documentation on std::string (okay std::basic_string) in "The C++ Standard Library" by Nicolai M. Josuttis. That all makes it seem like string is part of the STL. What's your argument that it's NOT part of the STL?

      std::string already has way too many member functions as it is

      string a("%03d %s %0.2f", 1, "hello", 2.75);

      Why is it so hard to imagine there are other, perfectly valid things you would want to do with a string? In another post in this thread, I also made the case for having unified, strict control over the implementation of case-insensitive comparisons. I have a hard time imagining a world where a spartan application-specific API is less effective than a rich application-specific API. I agree that trying to redesign the wheel, in adding "new and improved" methods to something as well designed as the STL is nuts - a lot of people try it, and they write crap. I'm talking about an application where there are consistent use patterns in the code, and unfortunately, they're spread all throughout the code. Wouldn't it be better to have a centralized place where those decisions could be controlled, audited, and tested as a cohesive whole? That's why I propose that in a larger application, it often makes sense to code classes to handle application-specific data in a unified way, as opposed to letting each coder make inline decisions while coding.

      As a general rule, adding member functions is bad

      What? Again, I'm not trying to make a general case for "down with STL" or anything inane like that. STL is fantastic! As a lowest-level in your application. That's my point. Just because the STL is great doesn't mean that it should be involved in all levels of an application's codebase. Specifically, application-specific data should be encapsulated from the application programmer as much as possible, so that changes can be made to the underlying design later. Of course, all of this should be done while providing the best possible API to the application-specific data. Well, what I'm proposing is that the STL is not the best API for all application-specific data. And that people should invent their own rich, application-specific APIs. (And if the underlying code behind their class is written using the STL, that's great - it's a rich toolset that's appropriate in many, many situations.)

      In other words, just because your language provides some trick (like STL), that doesn't free you from doing good OO design.

      --
      Education is the silver bullet.
    7. Re:Partial List by Viking+Coder · · Score: 2

      Your argument seems to add up to two things, if I may paraphrase :

      1. The STL is the best thing ever. In fact, the C++ standard comitee voted on it.
      2. Encapsulate your new "methods" outside class scope, but in a central, controlled location.

      Well, I disagree with your first point. I agree that you will have ownership problems if you mix metaphors, and one of the metaphors is a Has-A relationship. If worse comes to worse, I can provide a "data()" method, and later depricate it.

      As to your second point, you've got a very strong argument. Except when it comes to application-specific code.

      I've seen a lot of code where someone just decides that their class will be in a specific STL container, and that's the API for it. Sometimes, this is a rediculous way of doing things. In many cases, it is far, far better to provide a manager class that has a rich API, that happens to use STL as the back-end.

      I understand the value of generic programming. I really think I do. But when it comes right down to it, most applications have a lot more to do with specific programming. One set of tasks, repeated over and over again. Those kinds of things require OO design, and just because you use the STL, that doesn't give you free reign to ignore OO design - which is what I'm seeing. That's the point where I get frustrated that there isn't more code that's still written where a manager class Has-A container of another class. That's a great paradigm, once you get into a large-enough application with specific problems and complexities.

      To address a point of yours :

      Your own "myString" is not accepted as input by any other code.

      What "other code"? I'm involved in a huge application all written by one company - the company I work for. Now, perhaps I'm suffering from a case of Not-Written-Here, but think about it. If you used the str* functions all over the place, instead of making a class that used them, you had a major rewrite to switch to the STL. Why is it so hard to imagine that one day, something better than the STL might come along? Encapsulation is always good. And for God's sakes, think long and hard about using STL for your back-end, for the time being - it's fantastic! That's my point.

      I agree, string isn't the greatest example. I'm really talking more about intelligent, meaningful data structures in domain-specific code. Just because there's a list or map waiting for you, that doesn't mean that it's the best possible design for say, keeping track of which space shuttles are in orbit. Sometimes it makes a lot more sense to encapsulate those things, so some idiot programmer doesn't erase one of the shuttles, by mistake. See what I mean?

      --
      Education is the silver bullet.
    8. Re:Partial List by Viking+Coder · · Score: 2

      Do you even know what a template is? It's a type-parameter, nothing more, nothing less... there's no "protability problems" in templates for the simple uses of templates as type parameters.

      std::vector<std::string> myStringVector;

      Port that to Pascal, or Java, or Python. Or any other modern language.

      It's a gigantic pain in the ass. Once a large portion of the code in an application uses the STL to a large degree, you can not port the application to another language. The syntax is too different, and it will take a huge effort. Not that I think that porting to another language is a common occurance, but it does happen.

      That is incorrect. You may use typedefs.

      Typedefs don't encapsultate anything! I could take or leave the rest of your arguments, but this point is rediculous.

      The typedef keyword defines a synonym for the specified type-declaration.

      That's all it is, nothing more, nothing less - and a synonym doesn't encapsulate anything.

      but there's no reason not to use the C++ language to obtain best results

      Getting rid of the double-negative, you seem to be saying,

      always use the C++ language to obtain best results

      Maybe in a code-obfuscation contest! =)

      OO design is fantastic, and many languages provide a convenient way of using it. But the STL is not the end-all, be-all interface. As I said in another post on this thread, a std::list of space shuttles that are in orbit is a horrible API. Maybe that's the back-end, but that should NOT be the public interface. Because some idiot could accidentally erase one of the shuttles. Instead, those decisions should be tightly encapsulated in one place, and a convenient public API should be exposed.

      I think, you would probably find yourself better at home in the JAVA world?

      Let's all play nice, kids. There's no place for these kinds of insults in /. It's not like I'm Jon Katz, and I wrote an opinion piece about how the STL caused Columbine. =)

      --
      Education is the silver bullet.
    9. Re:Partial List by elflord · · Score: 2
      std::string, just like std::vector. Those seem homogenous to me.

      That they're in the same namespace does not make them "the same". Take a look at the designs of the two. They have very little in common.

      There's also documentation on std::string (okay std::basic_string) in "The C++ Standard Library" by Nicolai M. Josuttis. That all makes it seem like string is part of the STL. What's your argument that it's NOT part of the STL?

      Simple. It's not part of STL. This obviously begs the question, "what is STL ?". The Josuttis book is about the Standard library. This is NOT the same thing as the STL. The standard library includes strings, streams, and valarrays. STL doesn't. STL is the name of a library developed by SGI and HP that was incorporated into the standard. The string class was part of the library before STL, and was designed independently, which is why it isn't consistent.

      string a("%03d %s %0.2f", 1, "hello", 2.75);

      That's not even typesafe. You can do the same thing more safely using std::ostringstream. I'm not necessarily saying that there aren't "valid" things one may want to do with a string. My point is that none of these other things require additional member functions. In your above example, you could write a make_string() function that uses sprintf() to create your string.

      Wouldn't it be better to have a centralized place where those decisions could be controlled, audited, and tested as a cohesive whole?

      No. Smaller classes are easier to test, and less likely to break, because there are less entry points to the private data of the class, which makes it harder to violate class invariants.

      And that people should invent their own rich, application-specific APIs. (And if the underlying code behind their class is written using the STL, that's great - it's a rich toolset that's appropriate in many, many situations.)

      I agree with this. But I'd do this by adding non-member functions. STL containers are not designed for subclassing, and subclassing them will get you into a lot of trouble in short order (think about the assignment operator, exception safety, and depending on how you extend, the destructor)

    10. Re:Partial List by Viking+Coder · · Score: 2

      You're right. What I really meant to say was, "don't let the STL make design decisions for you, especially if you aren't yet really comfortable with the STL."

      And yes, I work in the medical field. =)

      --
      Education is the silver bullet.
    11. Re:Partial List by axlrosen · · Score: 2

      "The C++ Standard Template Library" by Nicolai M. Josuttis

      Actually it's "The C++ Standard Library", it covers more than just the STL. I've heard it's very good (www.accu.org).

    12. Re:Partial List by Viking+Coder · · Score: 2

      Of course typedef's ecapsulate (unless people actively circumvent it)

      I liked the rest of your post, and I don't disagree too vehemently with it. =) But this point is sadly mistaken. The only encapsulation is true encapsulation.

      The alternative is to essentially name your methods :

      please_Dont_Call_This();

      Or to say this :

      public: // this section is private! don't use it!

      If you work for a large enough company for a long enough time, someone is going to use something in the public ("private") section, someone is going to call please_Dont_Call_This, and someone is going to call map::const_iterator foo_it(foo.begin()).

      I agree with your assesment that it's good that it will break at compile time. Compile time is the best time to find errors. =) More people should try to write code that will run correctly IFF it compiles correctly. I see far too many tricks that leave everything until runtime, lately.

      I don't think "language portability" stand out as a quality in a program, but

      The main reason I like "language portability", is because not every coder learned to code in C++. When code is generally readable (meaning, it reads just about the same, no matter what language it's written in), coders are more likely to understand it, and to make fewer mistakes. Perl and some stuff in STL are not generally readable. *shrug* That's another reason why I love STL for an implementation, but I hate it for an interface to my code. (To steal a couple keywords from Pascal.)

      And by the way, C++ now has Garbage Collection, thanks to std::auto_ptr - another reason to be distrustful of STL. ;)

      Anyway, I may not agree with your opinions, but your thoughts are very well said - I commend you on your command of the language and the strength of your convictions. (Even though I hate what you're saying, I'd give you mod points, if I had them.)

      --
      Education is the silver bullet.
  26. Re:Memory Management by lkaos · · Score: 2

    Easy way to solve this problem known as the "swap trick." This will work with any container (and strings) and is the only way to guarentee a reduction in capacity.

    vector v(10000); //reserve bunch of memory
    //even though size is 0

    vector().swap(v); //swap the elements from an
    //empty temporary including
    //swapping capacity

    --
    int func(int a);
    func((b += 3, b));
  27. Bad inline optimisation. by Phil+Wilkins · · Score: 5, Informative

    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.

  28. Enterprise issues with STL by MobyDisk · · Score: 5, Insightful

    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.

    1. Re:Enterprise issues with STL by elflord · · Score: 2
      Disadvantages of STL:- Large executable file sizes

      While this is true, it's also worth mentioning that compiling with agressive optimisations (-O2 on gcc) makes a huge difference as far as executable size is concerned. For example, the 200k figure could probably be reduced by using optimisation switches. The inlining can sometimes be a blessing in instances where the template code "melts" to almost nothing after optimisation.

  29. Re:Lots of overhead. by Xentax · · Score: 2

    The tradeoff on binary size for code readability and maintainability (and execution time, of course) can be well worth it, IF you have the memory to spare. Our target machines rarely have less than 1GB of RAM, so it's not been an issue.

    --
    You shouldn't verb words.
  30. Re:Lots of overhead. by gergi · · Score: 2

    STL = Standard Template Library

    It basically defines a lot of common tools that you can use with your program specific needs such as lists and queues.

    --
    Nosce te Ipsum
  31. A couple STL issues by turnage · · Score: 2, Informative
    I have two big nausiating problems with STL (both of which are overcome by its pros).

    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.

  32. STL documentation by reynaert · · Score: 2

    SGI's reference is excellent. It covers the entire STL standard (the few SGI-specific extensions are clearly marked), and is very well written.

  33. Re:Lots of overhead. by PuntaConejo · · Score: 3, Informative

    Unlike an inheritcance-based container,
    like those in Java, the
    template-based containers of STL
    do not use virtual function calls to achieve
    genericity. Although this may result in an
    increase in code size, there are cases
    where different types can use the same
    code at runtime. For example, a container
    of int * and a container of char * might use
    the same object code.

    Some of the benefits of template-based containers
    over inheritance-based containers are:
    1) static type checking
    2) can hold non-class type objects.
    3) no virtual function call overhead.

    To elaborate on item 2: If you want a
    container of intgers in a Java container
    (i think) you have to have a container of
    "Int" rather than "int".

  34. Re:Lots of overhead. by MobyDisk · · Score: 2

    Standard Template Library

  35. Re:Lots of overhead. by Xentax · · Score: 2

    We had a nasty bug like that too -- the strange thing was that gcc was ok with the symbol name lengths when we compiled for debug, but something in our release build flags (the optimization level I think) would truncate the symbol names, which then caused naming conflicts, etc...quite a mess.

    Xentax

    --
    You shouldn't verb words.
  36. Re:Lots of overhead. by nonya · · Score: 2, Interesting

    Standard Tamplate Library. It is a standard C++ library that provides containers and generic algorithms. The power of the STL comes from abstracting the concept of a sequence - the algorithms work on linked lists, c arrays, vectors - anything that provides iterators. For example, the following function will return the sum of all the elements in a sequence (off the top of my head, did really compile this):

    template
    double sumOf(TIter start,TIter end){
    double result=0.0;
    for(TIter curElement=start;
    curElement!=end;
    ++curElement){
    result+=*curElement;
    }
    return result;
    };

  37. Re:Not all compilers support it, god-awful comp er by wurp · · Score: 2
    But it is a tradeoff between having more code or having better type checking.


    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.
  38. Embedded Platform Issues by omnirealm · · Score: 4, Insightful

    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
    1. Re:Embedded Platform Issues by Jherico · · Score: 4, Insightful
      Using STL may affect your portability, especially in the embedded systems arena.

      That's the stupidest thing I've heard all day. You switched from std::string to the MFC CString and you say that STL isn't portable? You don't need MFC's handholding. You go out and find one of the many copies of the STL that's freely available out there and you compile it yourself. You don't switch to something thats even LESS portable.

      --

      Jherico

      What can the average user can do to ensure his security? "Nothing, you're screwed"

    2. Re:Embedded Platform Issues by swillden · · Score: 2

      I've seen plenty of systems without enough storage to hold an stl library much less the library and all the application software.

      Umm, the project under discussion was on *WinCE*, which means it's nearly a PC.

      --
      Note to ACs: I usually delete AC replies without reading them. If you want to talk to me, log in.
    3. Re:Embedded Platform Issues by CoreyG · · Score: 2

      I just inherited a Bluetooth financial transaction system project and was wondering what freely available STL I should use? Thanks...

    4. Re:Embedded Platform Issues by Jherico · · Score: 2
      I just inherited a Bluetooth financial transaction system project and was wondering what freely available STL I should use? Thanks

      STLPort seems to be widely regarded as the best free implementation. My company uses dinkum STL, which is not free, but available for several platforms.

      --

      Jherico

      What can the average user can do to ensure his security? "Nothing, you're screwed"

    5. Re:Embedded Platform Issues by CoreyG · · Score: 2

      Yeah, my parent post was supposed to be a play on two posts above, this one and this one. Wooosh! Oh well...

    6. Re:Embedded Platform Issues by elflord · · Score: 2
      So why'd you have to go and top it? Are you actually expecting people to be able to drop in 3rd-party STL implementations on an embedded system?

      STL is a source-code library. There is no STL runtime. In other words, you don't pay for what you don't use.

      However, STL classes are probably too big and complex for a lot of embedded systems purposes. Conservative applications of templates can work in embedded systems, but careful attention needs to be paid to code size, and STL is not optisimised for producing small code.

  39. this is wrong by Karma+Star · · Score: 3, Insightful

    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.
  40. too much time by 0WaitState · · Score: 4, Interesting

    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!
  41. Vendor specific by Zathrus · · Score: 5, Informative

    The biggest downside of the STL is when it doesn't work.

    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 /. more recently), and the executables are freaking huge.

    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.

    1. Re:Vendor specific by Viking+Coder · · Score: 2

      This brings up an interesting question for me.

      How the hell do people cope with Daylight Savings Time? How do you indicate whether 1:30 AM is the /FIRST/ 1:30 AM, or the /SECOND/ 1:30 AM, when Daylight Savings Time hits?

      --
      Education is the silver bullet.
    2. Re:Vendor specific by leshert · · Score: 2

      You never calculate anything using local time. You always calculate using GMT, and only convert to local time if it's necessary for user presentation.

    3. Re:Vendor specific by Amazing+Quantum+Man · · Score: 2

      You don't have to. When DST comes on, you skip an hour. The problem occurs when DST turns off.

      Remember, "Spring Forward, Fall Back".

      Anyway, the solution is:

      0130 PDT (first 1:30, DST)
      0130 PST (second 1:30, standard time).

      What's the problem?

      --
      Fascism starts when the efficiency of the government becomes more important than the rights of the people.
    4. Re:Vendor specific by Electrum · · Score: 2

      How the hell do people cope with Daylight Savings Time? How do you indicate whether 1:30 AM is the /FIRST/ 1:30 AM, or the /SECOND/ 1:30 AM, when Daylight Savings Time hits?

      You don't, plain and simple. Nasty things like time formatting and conversions should only be done when necessary, i.e. to display it to a user. No sane program (or programmer) would try to keep track of time in that format internally. The most common method of storing time is to use a UNIX timestamp, which is the number of seconds after the UNIX epoch ("1970-01-01 00:00:00 GMT"). The problem with this approach is that in 2038, a signed 32-bit number will overflow. It also means that times before 1970 and after the beginning of 2038 cannot be stored.

      A better approach is to use TAI64 or TAI64NA times. TAI is much more accurate (see the page for details), and does not have the range problems of UNIX timestamps. DJB's public domain libtai library allows you to store and manipulate dates and times on the TAI64 and TAI64NA time scales.
  42. heh... by rebelcool · · Score: 2
    only to call it in a class full of obscure ugly code :)

    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++.

    --

    -

    1. Re:heh... by zaphod110676 · · Score: 2, Insightful

      Well, that's just the thing. The point is that you shouldn't wait until you've implemented five levels of code before you start debugging let alone compiling. You code a class, compile it, test it as much as you can and then add another class. Repeat.

      The other issue is that you must plan ahead and think about what you are doing before you start coding. If you are going to code by the seat of your pants then OOP is a very bad idea. You are far too likely to program yourself into a corner. To be in a situation where something that is burried under five layers of classes needs something that is burried under five entirely different classes is a very frustrating situation. You can back yourself into that situaion with most any OO language.

      If you are going to code by the seat of your pants then you should write really ugly Perl. =)

      --
      To Do: 1. Take over world 2. Pick up Milk and Bread on the way home
    2. Re:heh... by Jay+L · · Score: 2

      The point is that you shouldn't wait until you've implemented five levels of code before you start debugging let alone compiling.

      The question is not when you start debugging.

      The question is when you expect to finish.

      If the answer is "never", then your code must be debuggable. STL isn't, at least not with today's compilers, although you can approximate it for the *common* errors with a sed script.

      If the answer isn't "never", rethink your answer.

      If the answer is not "never", you're wrong.

    3. Re:heh... by Jay+L · · Score: 2

      unless you mean the compiler error messages

      Unfortunately, that is what I meant. I used a sed script to replace string>>> 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...

  43. Probably slightly better than Fortran... by Zeinfeld · · Score: 2
    While C++ has not stopped moving yet it is clearly on its way to join Cobol, Fortran, Smalltalk and the rest as onetime mainstream languages that are no longer hot.

    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/
    1. Re:Probably slightly better than Fortran... by whizzird · · Score: 2, Informative

      At this point the momentum in the software industry lies firmly with Java and C#.
      Exactly what type of crack are you smoking?
      According to techies.com, C++ is the most requested language skill, and the second skill overall (after Unix), with Java close behind it. Java is not a good laguage for building large enterprise level systems. JVMs are too slow.
      More important...C++ jobs pay much better than Java jobs (and Unix pays better than windoze).
      I do C++ on Solaris and Linux, so I'm happy. :>

      As for C#. Who would ever use it? It only runs on windoze, which is rarely used in the enterprise, and it is slow, buggy, and relatively untested.

    2. Re:Probably slightly better than Fortran... by Zeinfeld · · Score: 2
      Smalltalk? Fortran? Surely you jest.

      Yes, sortof. The point is that ten years ago C++ was hyped to the same extent as Java is today, but that largely evaporated and today C++ is no more interesting than any of the other legacy languages. OK for getting a job but no longer considered the future direction of the industry.

      WRT your comments on Python etc (which I used back in '95) the most significant thing about C# is that Java is no longer the only player in town. Clearly Microsoft and many windows developers will be using C# and for them Java is an irrelevance. Java is no longer the only mainstream object oriented extension to C that is not as demented in syntax as C++.

      But as anyone who has used C# could tell you, .NET is not really about C#, all C# is is the C style syntax that accesses the .NET framework. There are already python and smalltalk compilers available.

      C#, smalltalk, Python are all languages that a sane person with knowledge of several languages could use from choice. I just don't believe Fortan, Cobol or C++ fall into that category.

      --
      Looking for an Information Security student project suggestion?
      Try http://dotcrimeManifesto.com/
  44. Advice from an STL battle-scarred veteran by MagikSlinger · · Score: 5, Informative

    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
    1. Re:Advice from an STL battle-scarred veteran by Teancom · · Score: 2

      "Fourth: Get a good C++ and STL implementation. If you don't, you could wind up with compile errors that will drive you insane. "

      Okay, now define "good c++ and stl implemtation" :-) In a scary form of kismet, I work for a small software devel team that is porting away from roguewave, and we are heavily considering the stl (two reason: tools.h++ is EOL'ed, and we want *good* linux support, which RW isn't providing). Which version of g++ should we be using? What version of the stl? You need to 'splain B-)

      Thanks.

  45. Why do a wholesale switch? by cfulmer · · Score: 3, Insightful

    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.

  46. Re:Lots of overhead. by Ozwald · · Score: 3, Informative

    Actually, STL is blistering fast and the size increase of marginal compared to a C equivelent. On some platforms (Linux being one), the STL code is in a shared library to reduce the executable size.

    Instead, imagine what you are gaining. You get a good string class. No more worring about if the buffer is big enough or having to realloc/free memory when a string is appended or no longer required. It makes buffer overflows history.

    Hash's and Trees: you can do this in C/Perl/Delphi/whatever, but STL's implementation is very easy to use and is optimized like crazy. The STL writers are very proud of their algorithms' performance. This may be one of the cases where it's impossible to write a faster C equivelent.

    Portability. Anything written in ANSI C++ will compile anywhere as long as the compiler and libraries are up to date. A program I am working on will compile on C-Builder 4, Visual Studio, and GCC on Linux, without a single #ifdef or third party library.

    The only downside I have experienced is that I needed to spend some money on books. STL has a learning curve and you might find yourself aging rapidly while fighting syntax errors that fill up the screen. But once you get the hang of it, STL is the easiest way.

    Ozwald

  47. Re:Not all compilers support it, god-awful comp er by reynaert · · Score: 2
    But the real bear is the compilation error messages, which can be pages long, and ultimately completely unreadable.

    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 :)

  48. We recently changed from RW to STL by AndSoitGoes · · Score: 2, Interesting

    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.

  49. mostly downsides by j09824 · · Score: 3, Interesting
    I think the STL has mostly downsides:

    • The STL makes no guarantees that it checks for errors (bounds checking, using a pointer into the wrong collection, etc.), and it is designed in such a way that error checking is quite costly. (Note that there have been a couple of attempts at making a safe STL; see here; it is unacceptable that this isn't part of the standard and isn't used by default).
    • It's hard to predict whether any particular data structure or algorithm is going to be fast. Sure, it makes asymptotic guarantees, but everybody does that; it's the constants that matter.
    • The library is too complex for most needs, and you can't easily just use "a little bit" of it. If you want to write efficient code using STL, you have to understand it pretty well.
    • STL's complex semantics also make thread safety hard to guarantee.

    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.

    1. Re:mostly downsides by lkaos · · Score: 2

      *The STL makes no guarantees that it checks for errors (bounds checking, using a pointer into the wrong collection, etc.), and it is designed in such a way that error checking is quite costly.

      Bounds checking is absolutely evil. An STL vector will perform exactly the same as a standard C array. If bounds checking was introduced, a vector would be between 3 and probably 20 times slower depending on the inliner.

      Bounds checking is the programming equivalent of training wheels. They seem like a good idea at first, but you should get rid of them as soon as possible.

      --
      int func(int a);
      func((b += 3, b));
    2. Re:mostly downsides by tommck · · Score: 2
      use the STL algorithms only if you don't care about performance.


      I'd like to see _any_ data to back up this implicit assertion that the STL algorithms are anything but very fast

      T

      --
      ---- It puts the lotion on its skin or else it gets the hose again. It does this whenever it's told.
    3. Re:mostly downsides by j09824 · · Score: 2

      The performance of STL algorithms is implementation dependent. You get good performance if you get a good implementation and if you use the right combination of algorithm and container. And that means that, for practical purposes, using STL algorithms is risky because you don't know what you are going to get in terms of performance.

    4. Re:mostly downsides by dhogaza · · Score: 2

      Which is exactly the thinking which has led to undetected buffer overruns being the most common bug leading to break-ins over the net.

      Our industry as a whole hasn't outgrown its need for training wheels. The argument that professional programmers don't need safety nets like bounds checking and the like was being made twenty, twenty-five years ago and was as stupid then as it is now.

      Amateurs don't need safety nets because no one uses their code and no one cares if it breaks.

      Professionals do, though. People use the code professionals write. When I'm riding on an airplane I care if the software breaks.

    5. Re:mostly downsides by j09824 · · Score: 2
      An STL vector will perform exactly the same as a standard C array. If bounds checking was introduced, a vector would be between 3 and probably 20 times slower depending on the inliner.

      For the STL, that is probably true, and it is one of the fundamental design flaws with the STL: bounds checking in the STL is very costly. The irony is that the STL has taken pointer arithmetic, which gave you a bit of efficiency on a PDP-11 with a dumb compiler, and turned it into a feature that makes the STL both unnecessary complex and very hard to bounds-check.

      But there is nothing inherently costly about array bounds checking. Modern processors are designed to implement it efficiently. In a well-designed template library, the overhead of array bounds checking should be less than a factor of 2.

    6. Re:mostly downsides by cpeterso · · Score: 2

      Replace it with:

      std::vector bufmem(n);
      char* buffer = &(bufmem.front());
      //...


      uh, sounds like you need an auto_ptr for arrays. I don't think the STL std::auto_ptr does not work for arrays, but the Boost libraries have a nice scoped_array for arrays.

    7. Re:mostly downsides by lkaos · · Score: 2

      But there is nothing inherently costly about array bounds checking. Modern processors are designed to implement it efficiently. In a well-designed template library, the overhead of array bounds checking should be less than a factor of 2.

      I fail to see the logic here.

      On an x86, an array can be indexed with one instruction (actually, the indexing can be used in any operation).

      So to say:

      a = v[1];

      would just generate something like

      mov DS:[ebp+12, 4, 1], eax
      mov eax, ebp+8

      Whereas with bounds checking you have have to introduce another register to hold the index, along with possible redirects and atleast 2 comparisions.

      Best case senario, you have 3 additional instructions and a redirect resulting in a factor of 4 overhead plus the possible cache miss from the redirect.

      Put that all in a tight loop, and bounds checking will kill performance.

      Now, if the compiler isn't smart enough to inline the now much more complicated operator, your also going to pay for a function call. That would be the kiss of death.

      --
      int func(int a);
      func((b += 3, b));
    8. Re:mostly downsides by Jay+L · · Score: 2

      I'd like to see _any_ data to back up this implicit assertion that the STL algorithms are anything but very fast

      Two or three years ago, in a high-volume e-mail-processing application running on Solaris and HP-UX, compiled with GCC 2.9x and the STL that came with it, found that c-strings performed significantly better than the much more elegant STL string class.

      I do realize that libstdc++ is probably farther along now, and that GCC 3.0 is out now, and I make no claim about any other compiler or STL implementation. But one of the most popular implementations of the STL *did* have performance problems with one of the most popular classes.

    9. Re:mostly downsides by tommck · · Score: 2
      The performance of STL algorithms is implementation dependent. You get good performance if you get a good implementation and if you use the right combination of algorithm and container. And that means that, for practical purposes, using STL algorithms is risky because you don't know what you are going to get in terms of performance.

      I believe that you get more of a performance issue when coders don't understand the implications of writing their code one way or another and use the wrong algorithm to get the job done. It's just like when you hand someone threads in Java. Next thing you know, everything's a thread!

      The standard _does_ spec the complexity of the algorithm used, though. I understand this isn't a hard performance requirement, but it's not like you're going to get an O(N^2) algorithm for a lookup on a map, either. You also have the option of switching to different implementations of STL.
      The right tool in the right hand is the only good way to get the job done

      T

      --
      ---- It puts the lotion on its skin or else it gets the hose again. It does this whenever it's told.
    10. Re:mostly downsides by jkujawa · · Score: 2

      There's a difference between writing truly secure software, and writing truly high-performance software. Most libraries aren't really targetted at writing secure software, they'd be too slow to use as a general case.

    11. Re:mostly downsides by j09824 · · Score: 2
      Whereas with bounds checking you have have to introduce another register to hold the index, along with possible redirects and atleast 2 comparisions.

      Yes, you need one register to hold the bound and you need one bounds check instruction, a single, fast, register-based operation. Neither is a big issue on modern processors. For the array indexing, you need to load the base, the index, add them, and then do the indirect load. Furthermore, you usually do something with the value, further amortizing the cost of the array bounds check. Overall, the overhead of array bounds checking in real programs is generally modest.

      In addition, if bounds checking had been part of the C++ standard library, compiler vendors would have gone out of their way to make compilers understand it and to add the right kinds of primitives to their libraries (and maybe the C++ standard) to make it as efficient as possible. Instead, we have vendors wasting their time on implementing the most obscure template features imaginable.

      Note that even on something as antiquated as the x86 architecture, you only need a single comparison, commonly and idiomatically expressed in C++ as "unsigned(index)>=unsigned(bound)".

      Furthermore, even if this modest overhead affects program performance, it usually does so only in a handful of cases in any real program. The correct solution is to have an optional unsafe subscripting operator that is used only in those few places where it is demonstrably important (and only conditionally after extensive testing even in those places).

      It just boggles the mind that something as dismissive of safety and debugging concerns as the STL could have been designed and accepted by a standards body in the 1990's. The STL is so fatally flawed that we would have been better off delaying ANSI C++ by another year or two than rushing it out the door with STL. But, I suppose, the situation is symbolic of the widespread disregard for software quality in the industry.

    12. Re:mostly downsides by j09824 · · Score: 2
      If catching bound exceptions is commonplace on your projects, either your programmers are poorly trained, or your design lacks sufficient abstraction.

      You see, I know that bounds errors are not common in my projects because I use bounds checking.

      Throw me something that will solve a problem I don't already have under complete control to begin with.

      How would you have a clue whether you have it under control? You don't test for it.

    13. Re:mostly downsides by j09824 · · Score: 2
      The standard _does_ spec the complexity of the algorithm used,

      Yes, which just goes to show how naive the standard is. Asymptotic complexity is neither necessary nor sufficient to ensure efficiency in particular applications. In some cases, an O(N^2) algorithm may be faster than an O(N log N) algorithm, in others it may not be. And if we look at "map", there are lots of O(log N) query data structures, and they are not at all interchangeable. The abstractions that STL presents simply break down when you are talking efficiency.

    14. Re:mostly downsides by tommck · · Score: 2
      Did you expect them to come out with a spec that says : "When you have a collection with 10 elements or less in it, it must take exactly 12.5ns on a Pentium III 700MHz" ? They can't spec _actual_ performance. There are too many variables. There are also way too many differences in C++ compilers and hardware platforms. That is why asymptotic complexity even exists, so that you can talk about performance of a particular algorithm. It is up to the developer to determine which container/implementation is proper for their particular requirements. It would be impossible to do otherwise.

      T

      --
      ---- It puts the lotion on its skin or else it gets the hose again. It does this whenever it's told.
    15. Re:mostly downsides by j09824 · · Score: 2
      They can't spec _actual_ performance.

      Yes, that's exactly my point. And because they can't, they should have concentrated on making the STL simple, safe, and focussed, instead of doing something enormously complex that still can't guarantee high performance.

    16. Re:mostly downsides by Jherico · · Score: 2
      The STL makes no guarantees that it checks for errors (bounds checking,

      Vectors are the only place you have bounds checking issues. vector::operator[] does not provide bounds checking. vector::at() does. That's the only difference. So you're dead wrong here. Its also very sad that no one else defending the STL has managed to point this out, demonstrating that even among its proponents, few really delve deep into the functionality to find what they want.

      using a pointer into the wrong collection

      I'm not sure what you mean here. First off, you should use iterators, not pointers, when dealing with the STL.

      It's hard to predict whether any particular data structure or algorithm is going to be fast. Sure, it makes asymptotic guarantees, but everybody does that; it's the constants that matter.

      And this is specific to STL as opposed to other libraries how? I mean except that the STL guarantees are WELL documented, and that anyone using the STL regularly should essentially know them well, and thus can be interchanged with anyone else who knows the STL well, leading to greater code maintainability.

      --

      Jherico

      What can the average user can do to ensure his security? "Nothing, you're screwed"

    17. Re:mostly downsides by Jherico · · Score: 2

      Jesus tapdancing christ! vector HAS optional bounds checking. Use the at() function instead of the [] operator.

      --

      Jherico

      What can the average user can do to ensure his security? "Nothing, you're screwed"

    18. Re:mostly downsides by tommck · · Score: 2
      Well, we differ there. I would rather have something standard which, given the proper implementation, _can_ be very nice in performance (and, in my experience most of them are faster that I would have written). I like the idea of the interface being known to everyone and being able to buy a fast implementation from someone like ObjectSpace, yet still remain standard. Otherwise, you have all these people learning proprietary collection/algo classes from job to job.

      T

      --
      ---- It puts the lotion on its skin or else it gets the hose again. It does this whenever it's told.
  50. It is hard to learn well by Henry+V+.009 · · Score: 5, Insightful

    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.

    1. Re:It is hard to learn well by egomaniac · · Score: 2

      All in all the STL is god's gift to programmers.

      You made a typo: "programmers" should have been "those, poor, poor bastards who are still stuck using C++".

      Just thought I'd point that out.

      --
      ZFS: because love is never having to say fsck
    2. Re:It is hard to learn well by Henry+V+.009 · · Score: 2

      Lisp certainly does not give you the control over the performance that C++ does. It blows C++ away in high level concepts, though.

    3. Re:It is hard to learn well by leob · · Score: 2
      The allocators are broken in my opinion. Using (different) customized allocators prevents interactions between your containers.

      I believe it is a good thing, otherwise things may get error-prone.

      There is another problem with allocators and STL: the standard does not require that the allocator-provided pointer types be used; so no matter what smart pointers you're using in 64-bit mode in your classes to reduce memory consumption, the STL containers may still use the basic 64-bit pointers. Some implementations are good, some are not so good, and trying to use STLport, IMHO, is a pain.

  51. STL and DLL don't mix well by Anonymous Coward · · Score: 2, Informative

    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.

    The main problem is that when useing templates the generated code is included in each translation unit (.o or .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.

    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.

  52. Object Lifetime Management by Waffle+Iron · · Score: 3, Informative
    The STL helps greatly to manage the scope and lifetimes objects vs. roll-your-own C datastructures and algorithms. However, once you put together a complex system it can still bite you if you're not extremely careful. STL data structures allow you to push C++ to a very high level of abstraction, but you should never forget that you're still using a relatively low-level language.

    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.)

    1. Re:Object Lifetime Management by sweet+reason · · Score: 2

      the STL is still the best thing about C++ and is just about the only reason I would use it instead of C

      an interesting comment. i use and like the stl, but the main reason i use C++ instead of C is that i far prefer object-oriented design and coding. i find C-style programming pretty painful since i started with OO (many years ago). do you not like OO, or is there something about the type of programming you do that makes it unimportant?

      --
      Everything should be made as simple as possible, but not simpler. -- A.E.
    2. Re:Object Lifetime Management by Waffle+Iron · · Score: 2

      I like OO fine. I guess I'm getting biased these days because now I tend to use very high-level languages and then add C or C++ extensions where needed. I use the OO features in the high level language, but extensions are usually simple enough so that they don't need it.

    3. Re:Object Lifetime Management by sweet+reason · · Score: 2

      I use the OO features in the high level language, but extensions are usually simple enough so that they don't need it.

      ah, i see. what high-level languages do you favour? (is this question going to start a religious war?) i have dabbled with perl and tcl/tk a bit, and smalltalk even less, but never got into them. are there high-level languages with strong OO? in perl it seems to be just tacked on, even more so than C++ tacks it on to C.

      --
      Everything should be made as simple as possible, but not simpler. -- A.E.
    4. Re:Object Lifetime Management by Waffle+Iron · · Score: 2
      My favorite is Ruby, which has a very clean OO design. Newer versions of Python (2.1, 2.2) are almost as good and more widely used; lately I've been developing mostly with Python 2.2.

      Some people swear by Objective Caml, which is a fast compiled functional/OO language, but my mind is a little to imperative to really get into it.

  53. It's a "nonstandard standard..." by dpbsmith · · Score: 2

    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.

    1. Re:It's a "nonstandard standard..." by dpbsmith · · Score: 2

      "I don't know what problem you ran into, but a conforming implementation of map would not have those performance characteristics. map.operator[] has O(log n) access time."

      Of course. It's SUPPOSED to have reasonable performance characteristics. That's why I figured it was OK to use.

      That's why I was SURPRISED when the access time was more like about O to the fifth power.

      As I said, you apparently can't trust vendor-supplied implementations of STL to behave as expected.

  54. Compilers are most important by andr0meda · · Score: 2

    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.

    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 /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.

    --
    With great power comes great electricity bills.
  55. Only a few downsides by isj · · Score: 2, Insightful

    The most important downside is that some people think that STL is the holy grail. Not so. There is no silver bullet.

    The abstraction level can also be a problem sometimes allthough this is not a problem only with STL. For instance a colleage of mine had to spend much time tracking down why 1 million elements of 48bytes each consumed 144MB. I have also seen the usual problem with someone testing if a list was empty by using size()

    Another downside is that the STL is a forced standard meaning that the standard was set before the compilers were able to fullfill it. It has gotten a lot better but you can still encounter limitations in all compilers.

    Non-obvious limitations is also a downside. The STL has a very clean design which (unintededly) leads to a few strange limitations, such as const_interators not having a != operator

    Sometimes programs using STL is harder to debug. It is not exactly pleasant to have a core dump deep inside template-template-template.....RBtree, spending some time figuring out what that is and after a few hours discover that the problem was not the container at all but something that had scribbled on a reference-copied string :-(

    The STl is subject to the usual problems with "Quality of implementation". The standard is set but the implementation has been left (third-party) vendors. Why didn't the Standard Committee provide a public-domain reference implementation which vendors could optimize?

    Finally, the STL some places show signs of "Design by committe". This can lead to overly complex designs or no design at all (if the committee cannot agree). Do we really need generic character support in basic_string? Which kind of bastard is auto_ptr? Where is the hash_map?

    This is not a rant. I use STL frequently. STL has a lot of advantages but the poster only asked for downsides. You just have to keep in mind that there is no silver bullet.

    1. Re:Only a few downsides by Sebastopol · · Score: 2



      Thanks to STL I know have a nervous pavlovian twitch response whenever i see the letters "_Rb_tree" anywhere.

      --
      https://www.accountkiller.com/removal-requested
  56. Re:STL Downsides? by lkaos · · Score: 4, Interesting

    1. It uses templates. I know the name implies this but I can't stand the way C++ implements templates. Templates are created at compile-time which removes any advantages of generics in the first place.

    As compared to what language??? C++ templates are one of the best features of the language. Yes, they are a different concept, but embrace it, change is good.

    I have no idea what you are talking about regarding templates being created at compile-time as being a bad thing. That's what generic programming is all about!!! Its the compiler generating classes so that you don't have to. It has to be done at compile time. I'd love to hear an example of a language that implements some kind of generic stuff at runtime.

    2. While it may reduce developer time, it doesn't reduce code bloat. Templates are huge wasters of memory. This is because C++ creates a brand new class for *each* type of the template you use. So if memory consumption is an issue for you (like it is with me) then stay away.

    Having additional classes only uses more memory at compile time. It makes absolutely no difference at runtime. The executable size increases only because of debug information. Stripping out the debug info will dramatically reduce executable size.

    3. Template are *not* portable. Each compilier has varying support for templates. Yes the *new* compiliers support *most* of the STL but if a developer wants to get to those older models on the shelves... stay away.

    ANSI C is *not* portable either for the most part. Remember, C++ is a young language with a young standard. Of course its not as portable as C, but its still more portable than any other solution (MFC, RougeWave, etc).

    4. Using templates is verbose especially when you decide to throw inheritence in there. Template may look cool but they can get complicated really quickly (i.e. using the STL map template while inheriting from it)

    YOU SHOULD NEVER INHERENT FROM AN STL CONTAINER. Period. There is no good reason to do this. If your design calls for it, then you have a bad design. Besides, STL containers do not have to have virtual destructors so you are introducing potential memory leaks if you inherent from them (this was made part of the standard on purpose).

    5. Fragile Base Class. This is a C++ problem but it very much applies to the STL. If you build anything upon the STL and they add a virtual function... good-bye binary compatibility.

    The STL does not have virtual functions. Nothing to worry about there. Remember, STL is standardized so there is no need to worry about stuff like that.

    I fight extremely hard to not use the STL as there are other well-tested non-templated implementations of what the STL has.

    For instance??? You are doing yourself an extreme disservice by avoiding STL.

    --
    int func(int a);
    func((b += 3, b));
  57. Re:Not all compilers support it, god-awful comp er by Mike+Connell · · Score: 5, Informative
    Just for the non C++ programmers, here's a (real) example of those STL template errors.
    readply.cpp:109: conversion from `_List_iterator<list<basic_string<c
    har,string_ch ar_traits<char>,__default_alloc _template<true,0> >,allo
    cator<basic_string<char,string_char_traits &l t;char>,__default_alloc_tem
    plate<true,0> > > >,const list<basic_string<char,string_char_traits&lt ;
    char>,__default_alloc_template<true,0> >,allocator<basic_string<char
    ,string_cha r_traits<char>,__default_alloc_template<t rue,0> > > > &,c
    onst list<basic_string<char,string_char_traits&lt ; har>,__default_alloc
    _template<true,0> >,allocator<basic_string<char,string_char _traits<c
    har>,__default_alloc_template<true,0> > > > *>' to non-scalar type `
    list<basic_string<char,string_char_traits&lt ; har>,__default_alloc_temp
    late<true,0> >,allocator<basic_string<char,string_char _traits<char>,
    __default_alloc_template<true,0> > > >' requested
  58. Erasing stuff from a vector by hawkestein · · Score: 2


    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?
    1. Re:Erasing stuff from a vector by Viking+Coder · · Score: 2

      Thanks for pointing this out - I knew I should have been more clear. If I have an element, and I want to remove it from a vector, I have to write a bunch of code. I have to find it first, make sure I actually found an element, and THEN I can erase it. This means I either keep a local copy of the iterator, or I call the find_first algorithm twice.

      It's kind of like the hoops you have to jump through to do a case-insensitive compare on strings.

      I really don't like functors. If people aren't careful, they end up implementing the same functor in multiple locations. I think the method paradigm is much better, because they're tightly coupled with the class that they act on. Functors can live just about anywhere - and you can end up with duplicated effort (ie bugs), once a project gets large enough.

      Also, I dislike the fact that some STL functions will return "npos" and some "::end()" to indicate "no results".

      Again, that's just my opinion - I could be wrong.

      --
      Education is the silver bullet.
    2. Re:Erasing stuff from a vector by Viking+Coder · · Score: 2

      test.erase(find(test.begin(), test.end(), 7));

      What if the element 7 is not found? Obviously, it will be, in this simple example, but what if it's not?

      Then find returns last, in this case, test.end().

      And then, what happens when you say this?

      test.erase(test.end());

      BOOM. The most obvious way to solve this is to have a local variable, an iterator which stores the temporary result of the find, which you can compare to test.end(). Or you can put it all in one line, and call find twice.

      I don't particularly like either option. Especially for something as seemingly simple as removing a specific element from a vector, if it exists.

      Now, I'm not concerned about this simple case. I'm talking more about very deep application-specific code. And this is one example where the API of STL isn't too rich. That's the point where you say, "Ah-ha! I know, I'll make my own application-specific class, and provide a rich API for doing exactly that kind of thing." (And for some reason, a lot of people are getting really pissed off at me for suggesting that the STL isn't the Holy Grail.)

      --
      Education is the silver bullet.
  59. Downsides to STL using Windows by SloppyElvis · · Score: 2

    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.

    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 .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

    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.

  60. vector - vector<bool> by lkaos · · Score: 3, Funny

    Stupid HTML

    --
    int func(int a);
    func((b += 3, b));
  61. Re:Overhead by PD · · Score: 2

    Not true. You can stick pointers into the containers with as much ease as putting objects into the containers. The problem you have is freeing all the pointers when all the references go away.

    I use the Boehm collector, a custom allocator, and specializations of the containers to solve that problem. If you read a good STL book, they will probably solve that problem with smart pointers.

  62. Re:Lots of overhead. by jason_watkins · · Score: 2, Interesting

    Ok, glad you acknowledge that STL has nothing to do with virtuals.

    So yes, let's say you have a templated class and instantiate it for 15 different type specalizations. What's the memory overhead of this? Not much.

    On top of that, if you really do have 15 differen things, how are you going to shave off that overhead using a different mechanism? Will you create 15 seperate classes intead? That's even MORE overhead than the templating. Will you create one class with a type = field? Use comparision in all functions that relate to the class with seperate paths where needed for each of the 15 different cases?

    I hope you're starting to see that if you *really* have 15 seperate things, you pay that overhead no matter if you're dealing with ansi c using templates.

    These are criticisms that are parroted over and over without much understanding of what's going on. Please don't perpetuate ignorance. Go test it yourself, see the results.

  63. Re:Not all compilers support it, god-awful comp er by PD · · Score: 2

    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.

  64. Not necessarily by devphil · · Score: 2


    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)
  65. Re:What virtual functions? by lkaos · · Score: 5, Informative

    The number of abstract data types IN NO WAY AFFECTS CODE SIZE. Sorry to say it loudly but too many people here keep repeating that.

    It may *appear* that way when working with STL but that is only because of the debugging information. Using templates will increase the amount of debug information in the executable (for each instance of the template) but it does not increase code size in any noticable manner.

    Note: Ok, there are some methods that do get regenerated per-data type but the overhead is small and STL uses extensive inlining so this is almost meaningless.

    --
    int func(int a);
    func((b += 3, b));
  66. Debugging templates is hell by IvyMike · · Score: 3, Informative

    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.

  67. No Choice by TrumpetPower! · · Score: 2

    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.
  68. Experience with STL on multiplatform by Tiger · · Score: 5, Interesting

    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.

    1. Re:Experience with STL on multiplatform by leshert · · Score: 2

      We're running into the same issues as you with the memory high-water marks. How do you deal with them?

    2. Re:Experience with STL on multiplatform by vidarh · · Score: 2
      Huh? That would be absolutely horrible. When you use a const iterator (as the poster you replied to suggested), you most certainly want it to give you a const object. Thats the entire purpose of using const iterators after all: to have the compiler warn you if you try to mutate any objects.

      Writing const correct programs can be a pain sometimes, but when your core classes are const correct and you try to stick to const values as much as possible it's so much easier to catch stupid errors.

    3. Re:Experience with STL on multiplatform by vidarh · · Score: 2
      The we agree - the error messages are horrible. The problem is that they are horrible because they try to show in detail what is wrong. A typical example would be how typedefs appear in their full expanded glory instead of referenced by the typedef'd name. Sometimes this is useful, but more often it is not.

      I'm sure compiler developers will start producing more sensible error messages at some point...

  69. Re:What virtual functions? by randombit · · Score: 3

    If I use *vectors* to hold fifteen different types of objects, then I'll be using at least fifteen different vectors and causing fifteen different classes to be generated.

    Yes, 15 different classes, but the overhead, in almost all implementations, is very very low, because each of these 15 different classes has most of their code stored in type independant storage.

    For example, the map type stores it's stuff in a red-black tree. In the implementations I've seen, the map type just forwards most of it's calls into an internal object that does almost all of the actual work, and which is NOT a template, so only one copy of that code exists. These internal types aren't type safe at all; they rely on the external interface to ensure that they are used safely.

  70. Traps for the Unwary by Greyfox · · Score: 4, Insightful
    The biggest downside is that it's easy for an innocent array index operator ([...]) can do Strange Things. Things like creating object instances which will then immediately be destroyed after a test is made. This can make a serious dent in the speed of your code. Most of the good STL books you can get from your favorite bookstore cover the ins and outs of these pitfalls pretty well.

    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?

  71. Re:Templates increase code size? by mikeb · · Score: 2, Informative

    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.

  72. STL strengths and weaknesses by eddeye · · Score: 3, Interesting

    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.
  73. Re:Not all compilers support it, god-awful comp er by PuntaConejo · · Score: 2, Interesting

    >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.

  74. Re:pros and cons of STL by tps12 · · Score: 2

    Why did you post this excellent and informative message anonymously? I love "deferred addressing" and "metacircular allocation"...

    --

    Karma: Good (despite my invention of the Karma: sig)
  75. Why is inheriting from an STL class such a bad thi by hawkestein · · Score: 2


    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 &lt int &gt {
    public:
    typedef vector&lt int &gt base;
    using base::iterator;
    using base::begin;
    using base::end;
    using base::operator[];
    using base::size;
    // etc.

    // Here you'd add your own methods
    };


    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?
  76. Debugging is the downside by baxissimo · · Score: 5, Insightful

    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.

    1. Re:Debugging is the downside by Amazing+Quantum+Man · · Score: 2

      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.

      Ada 95?

      --
      Fascism starts when the efficiency of the government becomes more important than the rights of the people.
    2. Re:Debugging is the downside by Jester998 · · Score: 2

      "Sorta like how you can put a screw in a wall with a hammer -- you get the job done, but it's not exactly the way you want to do it and it could be a messy process."

      Uh, bad analogy. You are, after all, talking to a community of people who routinely carry LARTs in their back pocket...

      - Jester

    3. Re:Debugging is the downside by jejones · · Score: 2

      Come to think of it, couldn't one do something like the "metaprogramming" in PL/I with its preprocessor?

    4. Re:Debugging is the downside by Oink.NET · · Score: 2
      Sounds to me like it's time for some new language stud to come and save us.

      I think the language stud you're looking for is Anders Hejlsberg, the creator of the C# language. Although generics aren't in the current version of the language, they have them working in a research version, and the Common Language Runtime has been designed from the beginning to support them. A future future version of C# will most definitely support generics.

      From an interview with Anders:

      I definitely think generics are a very useful concept and you can certainly tell that from all the generics research that's taking place in academia and industry. Templates are one solution to the problem. In our internal discussions, we concluded that we wanted to do it right for this new platform. But what we would really like is to have generics understood by the underlying runtime. This is different from how some of the generic prototypes have been built. Take Java's notions of "erasure" where there's really no knowledge of generics in the system. By having the common language runtime understand the concept of generics, multiple languages can share the functionality. You can write a generic class in C# over in one place and someone else using a different language can use it.

      But making generics part of the runtime also enables you to do certain things much more efficiently. Instantiation of generics should ideally happen at runtime. With C++, instantiation of templates happens at compile time, and then you have two options: you can either let your code bloat or you can try, in the linker, to get rid of some of the bloat. But, if you have multiple applications, you can forget about it. You're just going to get bloated code.

      If you push the knowledge of generics into the common language runtime, then the runtime can understand that when an application or a component asks for a list of "Foo's," it should first ask: "Do I already have an instantiation of a list of "Foo?" If so, use that one. Indeed, if Foo is a reference type, and if we do the design right, we can share the instantiation for all reference types. For value types, such as ints and floats, and we can create one instantiation per value type. But only when an application asks for it. We've done a lot of the design work and groundwork necessary to add generics to the runtime.

      It's interesting you asked earlier about the IL because deciding to add generics impacts the design of the IL. If the instructions in the IL embed type information -- if, for example, an Add instruction is not an Add, but is an Add int or an Add float or an Add double -- then you've baked the type into the instruction stream and the IL is not generic at that point. Our IL format is actually truly type neutral. And, by keeping it type neutral, we can add generics later and not get ourselves into trouble, at least not as much trouble. That's one of the reasons our IL looks different from Java byte code. We have type neutral IL. The Add instruction adds whatever the two things are on top of the stack. In a generic world, that could translate into different code when the generic is instantiated.

      Osborn:
      Is that available to all .NET languages?

      Hejlsberg:
      Yes. Microsoft Research in Cambridge has created a generics version of the common language runtime and the C# compiler. We're looking at how to move that forward right now. It's not going to happen in the first release, that much we know, but we are working on making sure that we do things right for the first release so that generics fit into the picture.

      More detailed information on C#'s generics implementation can be found here.

  77. stlport by Screaming+Lunatic · · Score: 2
    I highly recommend STLPort. This makes sure that when you're using VC++ for windoze and gcc for *nix that everything will still be cross-platform and as you expect it. The VC++ implementation of the STL is not that great (surprise!).

    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.

  78. Re:STL Downsides? by Jherico · · Score: 3, Insightful
    Having additional classes only uses more memory at compile time. It makes absolutely no difference at runtime. The executable size increases only because of debug information. Stripping out the debug info will dramatically reduce executable size

    Sorry, no. If you're working with multiple DLL's and you access a std::list declared in some header from both of them, functions that you call in both DLL's will be located in both DLL's Thus code bloat. For a monolithic application, you are correct.

    YOU SHOULD NEVER INHERENT FROM AN STL CONTAINER. Period. There is no good reason to do this. If your design calls for it, then you have a bad design. Besides, STL containers do not have to have virtual destructors so you are introducing potential memory leaks if you inherent from them (this was made part of the standard on purpose).

    That's a pretty broad statement, and again I disagree. Suposing you want to create a string class with a subset of the functionality in std::string? Do you re-implement it? Supposing you want to create a structure that is best expressed as a list, but has just a little more functionality? Granted, you have to keep a pointer to the derived class, because of the virtual dtor issue, but its not completely unheard of.

    --

    Jherico

    What can the average user can do to ensure his security? "Nothing, you're screwed"

  79. Thread-safe string by devphil · · Score: 2


    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)
    1. Re:Thread-safe string by jkujawa · · Score: 2

      It's not, at least in older versions of libstdc++.
      The problem lies in caching the representation for efficiency. If a string is copied, and the copy is used in a different thread, bad things can happen.

    2. Re:Thread-safe string by Xentax · · Score: 2

      We were using a version of gcc no later than 2.95, and we started on Solaris 2.6 (moving to Solaris 8 as follow-on work, and so on).

      Actually, I'm not even sure which version of gcc we _started_ with on the project I'm thinking of, it may have been 2.71...

      (to related posts) I wouldn't be surprised if re-allocation was faster than locking/unlocking; we certainly saw cases at the speeds we needed where locking was entirely too expensive a bottleneck, including simply for string manipulation (which we'd already minimized as you would expect).

      Xentax

      --
      You shouldn't verb words.
    3. Re:Thread-safe string by devphil · · Score: 2

      Wow. I thought I was the only person still alive who used 2.7. :-) Wasn't that just a kick to work with...

      --
      You cannot apply a technological solution to a sociological problem. (Edwards' Law)
    4. Re:Thread-safe string by Xentax · · Score: 2

      Hey, gcc is the worst compiler in the world -- except for all the other ones out there.

      2.95 definitely made me happier than 2.71, though. We started with Sun's Forte/CC/we-can't-decide-what-to-call-it compiler, so it could have been worse ;)

      Xentax

      --
      You shouldn't verb words.
  80. it's butt ugly and impossible to maintain by small_dick · · Score: 4, Interesting

    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.
    1. Re:it's butt ugly and impossible to maintain by elflord · · Score: 2
      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.

      You've got to be kidding! Java does not even have typesafe collection classes, and there appears to be various pushes in the java community to get parameterised types working ...

  81. The STL, by a longtime user by Animats · · Score: 5, Interesting
    The STL is a reasonably good collection library. I wasn't initially too happy with the iterator paradigm. The idea of generalizing pointer arithmetic, the most error-prone feature of C, seemed a terrible idea. But it's worked out moderately well, and STLport can be compiled with iterator checking, which is very useful.

    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.

    1. Re:The STL, by a longtime user by dimator · · Score: 2

      This should get better soon, since Herb Sutter and Stan Lippman are both at Microsoft now, and seem dedicated to standards compliance

      BillG: So, Stan and Herb, I understand you two are working on standards compliance?
      Stan & Herb (look up from monitors): Yes, we feel its very important to be compliant with all standards.
      BillG: "Standards", aye? That's very interesting. But would you rather do that all day, or come see what I have parked outside for both of you?

      --
      python -c "x='python -c %sx=%s; print x%%(chr(34),repr(x),chr(34))%s'; print x%(chr(34),repr(x),chr(34))"
    2. Re:The STL, by a longtime user by tqbf · · Score: 2
      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.

      Obviously not, because the containers rely on the safety of the copy constructor and auto_ptr implements RAII through the copy constructor. Conceptually, aren't both part of the "STL" anyways?

      This is one of the reasons Boost has a templated shared_ptr, which does reference counting instead of source/sink pointers.

      This is covered in Effective C++, but it's also pretty obvious from the APIs.I question designs that want source/sink pointers in containers anyways; part of the idea behind using containers is to centralize the storage of objects.

      In practice, the big problem with the STL is that Microsoft doesn't like it. ... So they support it, but badly.

      I'm not sure this is a valid criticism:

      • Microsoft uses Dinkum STL, which is actually an exceedingly good implementation. The only problems I've had are concurrency issues.
      • Compare Microsoft's problem to Solaris. Forte uses bizarro Rogue Wave STL, which is not an exceedingly good implementation of the STL.
    3. Re:The STL, by a longtime user by dimator · · Score: 2

      A) My implication was that Gates is a money grubbing whore, trying to influence others like a drug dealer.
      B) It was a joke, relax.

      --
      python -c "x='python -c %sx=%s; print x%%(chr(34),repr(x),chr(34))%s'; print x%(chr(34),repr(x),chr(34))"
    4. Re:The STL, by a longtime user by Ayende+Rahien · · Score: 2

      there is a compiler switch for it, btw.

      --

      --
      Two witches watched two watches.
      Which witch watched which watch?
  82. Threads/Performance/Complexity by cthrall · · Score: 2, Informative

    > 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).

  83. Re:Lots of overhead. by angel'o'sphere · · Score: 5, Informative

    LOL

    moded as interesting but plain wrong.


    but there is a lot of overhead with using the STL.


    No there is no overhead in terms of speed. The STL is designed to yield as efficient code as a VERY GOOD coder would get by hand coding. As the STL is coded with "how will the compiler work on this" in mind its often far more efficient than hand crafted code ever will be. (e.g. inlining over several function calls in depth)

    Virtual functions and things of that like can make your code bigger and slower.

    In the STL there are only few virtual functions. Most are non virtual.

    Also a non virtual call costs you about 8 bytes asuming a 4 bytes instruction and 4 bytes adress, where as a virtual call you cost about 16 bytes, load register with adress, two times 8 bytes and jump idirect with register and offset, again 8 bytes.

    However in practice the latter case is often only slightly bigger than the former(depending on the instruction set of the CPU).

    If the code will be bigger than without STL is a question how your compierl and linker treat templates.

    And it is a question how you would replace templates by hand.

    Regards,
    angel'o'sphere

    --
    Cost free eBook I read (by iBook/Kobo/Amazon/ObookO/Gutenberg etc.): "The Green Odyssey" by Philip Jose Farmer.
  84. Re:STL Downsides? by bssea · · Score: 2, Insightful

    C++ templates are one of the best features of the language. Yes, they are a different concept, but embrace it, change is good.

    They are no different than a majority of languages out there. Remember that C++ got it's roots from elsewhere.. C++ is anything but different and original. Change is not always good.. especially when the implementation is bad, IMO.

    I have no idea what you are talking about regarding templates being created at compile-time as being a bad thing. That's what generic programming is all about!!!

    No sir. Generics should be resolved at run-time as much as possible (that is why they added RTTI to C++). With templates being done at compile-time it removes my ability to extend my Linked List to use basic_string and ints without adding yet more code. Templates suck at being generic, especially when you want it at runtime.

    Its the compiler generating classes so that you don't have to. It has to be done at compile time. I'd love to hear an example of a language that implements some kind of generic stuff at runtime.

    Smalltalk, Python, Dynace, Objective-C and even C... all nice languages

    It makes absolutely no difference at runtime.=

    I beg to differ. *every* template you instantiate adds to the binary size because of the need to use them. If I create a vector<string> and vector<int> I get *two* vector class and it will increase the binary size accordingly. Another downfall is that you can't mix and match types, so you have to encapsulate your nodes in yet *another* class... adding even more to the binary.

    C++ is a young language with a young standard.
    Even more reason not to use it!! the STL is *not* standardized, check your implementations.

    YOU SHOULD NEVER INHERENT FROM AN STL CONTAINER. Period.
    I disagree. You want to extend an STL containter to create better ones.

    Remember, STL is standardized so there is no need to worry about stuff like that.

    STL is *not* standardized...

    For instance??? You are doing yourself an extreme disservice by avoiding STL.

    hmm.. wxWindows, QT, Gtk+, Plib, and any other library that wishes to be *portable*. IMO, you do yourself a great disservice for using the STL.

    --sea
  85. Re:What virtual functions? by angel'o'sphere · · Score: 2


    But templates increase code size as the compiler has to genarate a different version of the class for each unique instance that you use.
    i
    e. If you use a Vector to hold 15 different things, the compiler has to generate 15 different version of the Vector class to compile your project.


    Right but wrong.

    I think you won't use vectors of Objects but vectors of pointers or vectors of references, right?

    So all "instances" which the compiler is generating are the same in terms of cpu instructions.

    A good compiler/linker sees that and removes the duplicated code.

    Again, the question I allways ask: if you would do it by hand, how would *you* do it? Writing a List_of_Strings class and a List_of_Persons class?

    And that does NOT duplicate code?

    The STL takes care to use sophisticated inheritance, template specialization and delegation to derive special cases from common abstractions.

    The more you use the STL in one single project the less code is added for ech additional application of the STL, as it is likely allready included somewhere else.

    Regards,
    angel'o'sphere

    --
    Cost free eBook I read (by iBook/Kobo/Amazon/ObookO/Gutenberg etc.): "The Green Odyssey" by Philip Jose Farmer.
  86. Downsides by Ken+Treis · · Score: 3, Interesting

    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.

  87. Some is way too verbose by RovingSlug · · Score: 2

    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).

    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 ::iterator.

  88. Is it just me.. by Backov · · Score: 2, Insightful

    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.
  89. maybe because MS doesn't implement the standard. by Tim · · Score: 2

    "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?
  90. Only One Serious Drawback by angel'o'sphere · · Score: 2

    The main draw back is the learning curve.

    Probably there is a further one: getting your team mates as enthusiastic as it is needed to get progress and benefit ... and fun, into the development.

    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.
  91. This is what I like. by rebelcool · · Score: 2
    People finally moving past the herd mentality of 'what? C++ is the greatest thing ever..never question it!' and looking to see how its quickly becoming obsolete. Or at the very least, having a difficult time supporting modern programming concepts in a sensible, maintainable way.

    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.

    --

    -

    1. Re:This is what I like. by Oink.NET · · Score: 2
      C# and the rest of the mainstream languages (java, python, perl, whatever) can do none of the thigs that c++ can do.

      Maybe not now, but a research version of C# currently supports generics, which is what C++'s STL is all about. The next commercial version of the C# language will have generics support. Read here for more information.

  92. * is faster than C (??) by Ars-Fartsica · · Score: 5, Insightful
    Every time someone trumps up the merits of their language, they always mention that it is (potentially) faster than C. This has been uttered so many times that I don't know why anyone uses C at all, it clearly has terrible performance (according to all the language advocates).

    I'm calling your bluff. Give me some stats for example programs.

    1. Re:* is faster than C (??) by Paul+Komarek · · Score: 3, Funny

      I thought you might be interested in some counterexamples. I don't think Intercal or Befunge advocates have ever claimed those languages were faster than C. In fact, I don't think they claimed Intercal or Befunge was better than any other language.

      -Paul Komarek

    2. Re:* is faster than C (??) by leshert · · Score: 4, Interesting

      The most well-known example is using the sort algorithm instead of C's qsort. Because all the comparisons are templatized, and you never end up casting anything to void*, all the comparisons are inlined, and sort shames qsort.

      When I tried it last, I didn't get the 6x difference some people claim, but it was about 2.5x faster.

    3. Re:* is faster than C (??) by Skapare · · Score: 2

      Every language has some bad features; things to be avoided. In fairness, we should compare best practices in C against best practices in C++, where the best practices is geared toward the specific goals (speed of execution, size of stored program, size of memory footprint, memory allocation usage, development time, reliability, readability (in context of a programmer skilled in that language) or whatever) one might have. I can assure you that qsort is among the many things in C to be avoided. Those things that are to be avoided in C++, should be as well, to be fair (but I don't know what they specifically are).

      --
      now we need to go OSS in diesel cars
    4. Re:* is faster than C (??) by Garen · · Score: 2, Interesting

      Some stats? Just by knowing how much more well-defined C++'s type-system is compared to C is enough to get an intuitive sense that there will be cases where C++ will out-perform it. As for a specific example, type-based alias analysis is one that seems to have been getting attention lately. C++'s templates, are probably the most remarkable example, as they can permit optimizations beyond the ability of current Fortran compilers.

      Both of them are so fast already though that comparing them for the most part isn't all that interesting. Awhile back, Alexander Stepanov created the Abstraction Penalty benchmark to test the effect of using abstraction features in C++ like the STL. Over the past several years I've noticed that the penalty is usually close to nothing, if not sometimes less than -- indicating a speedup.

    5. Re:* is faster than C (??) by Anonymous+Brave+Guy · · Score: 3, Interesting

      I think the key point here is that you can write an efficient, generic sort algorithm in C++ using templates. The closest equivalent in C, short of hand-coding a specialised version every time you use it, requires an indirection via a pointer at the least. Thus C++ does indeed provide a more powerful and probably faster way to solve this particular class of problems.

      --
      If you disagree, post your argument. (-1, Overrated) isn't your personal censorship tool for views you don't like.
    6. Re:* is faster than C (??) by Skapare · · Score: 3, Interesting

      If you hand code a new implementation every time you need to do sorting in C, then you are doing programming the wrong way. Ever heard of re-usable code? And if you limit you scope to the libraries that come with the languages, you're missing the potential. Look at PERL, for example. What comes with the language pales in comparison to all the cool stuff you can find online. And those things are used to promote the benefits of PERL.

      I do note your focus on the indirection the stock qsort in the C library uses. Sure, it slows things down a bit. I guess I can count you in the group who says that Java and C# are completely worthless because of the much slower speed they operate? :-) Execution speed isn't everything all the time. Sometimes it is, but not all the time. And often, for cases where one might use qsort, there are often better ways to organize thing, anyway. If you have a huge array in memory that you need to sort, perhaps the design is all wrong in the first place.

      --
      now we need to go OSS in diesel cars
    7. Re:* is faster than C (??) by Arandir · · Score: 2

      Regardless of what anyone may tell you, C++ is still C. If you can do it in C you can do it in C++ just as fast.

      The advantages of the STL sort over any comparable C sort, is that the former has a generic interface with a specific implementation produced at compile time. You just can't do this in C (yet).

      In order to get a generic sort in C, you have to use void* somewhere. That casting is going to slow you down ever so slightly. Imagine you can write a sort algorithm specifically dedicated to sorting lists of MyStruct's. In order to make this algorithm work with YourStruct's you have to create a virtually identical algorithm that merely replaces "MyStruct" with "YourStruct".

      That is *exactly* what the STL does!

      The disadvantage of the generic STL sort is that you can't tune for your data. But the same disadvantage applies to your generic C sort with void pointers. To balance this out somewhat, you also have the ability to specialize sort.

      --
      A Government Is a Body of People, Usually Notably Ungoverned
    8. Re:* is faster than C (??) by leshert · · Score: 2

      Umm... you've just lost the point of this thread. The original poster was complaining that while people claim C++ can be faster than C, he wasn't convinced. In fact, the exact words were, "I'm calling your bluff.".

      I responded with a case in which C++ was faster than C, and now you say "I guess I can count you in the group who says that Java and C# are completely worthless because of the much slower speed they operate?" Huh?

      I do almost all my day to day coding in C++ and Python, with some straight C when that's what the rest of the project uses and needs. Hardly a worshiper of the little tin god.

    9. Re:* is faster than C (??) by ttfkam · · Score: 2

      http://www.research.att.com/~bs/new_learning.pdf

      or in HTML but not as pretty (thank you google)

      http://216.239.51.100/search?q=cache:xGAGrn9SmD8 C: www.research.att.com/~bs/new_learning.pdf+%22Learn ing+Standard+C%2B%2B+as+a+New+Language%22&hl=en

      --

      - I don't need to go outside, my CRT tan'll do me just fine.
    10. Re:* is faster than C (??) by Anonymous+Brave+Guy · · Score: 2
      Casting pointers is free isn't it?

      Yes (in this context), but dereferencing them isn't.

      --
      If you disagree, post your argument. (-1, Overrated) isn't your personal censorship tool for views you don't like.
    11. Re:* is faster than C (??) by Anonymous+Brave+Guy · · Score: 2

      Sorry, but I think you've totally lost the plot here. This subthread began with a request for an example where C++ can be faster than C, and answers from two of us suggesting the sorting algorithms as such an example.

      If you hand code a new implementation every time you need to do sorting in C, then you are doing programming the wrong way. Ever heard of re-usable code?

      Sure. And writing such reusable code in C essentially requires a level of indirection. Writing the equivalent in C++ can be done without that, by using templates instead, and thus avoid the overhead. Hence the example at least two of us provided, that std::sort in C++ is likely to be faster than qsort in C. And that answers the original question.

      I do note your focus on the indirection the stock qsort in the C library uses.

      No, I focus on the level of indirection any C-style approach (short of macro gobbledegook) requires, and the fact that such an overhead is not necessary with the C++ templates approach. If you think you can write a generic sort algorithm in C that is better than a C library's qsort, and with equal generality and speed to typical std::sort implementations in C++ libraries today, I'd love to see it.

      I guess I can count you in the group who says that Java and C# are completely worthless because of the much slower speed they operate? :-)

      You'd guess wrong. :-)

      Both have their uses, and the speed issue may not be imporant in a given project. However, in the context we're discussing, the C++ standard library containers and algorithms are so far ahead of the closest equivalents in "standard" Java and C# as to be beyond useful comparison. This is not a troll, but a purely objective statement of fact: just look at what you can do with each, and how hard it is.

      And often, for cases where one might use qsort, there are often better ways to organize thing, anyway. If you have a huge array in memory that you need to sort, perhaps the design is all wrong in the first place.

      Sure. But perhaps it's not. :-)

      --
      If you disagree, post your argument. (-1, Overrated) isn't your personal censorship tool for views you don't like.
  93. Re:What virtual functions? by Anonymous Coward · · Score: 2, Informative
    The number of abstract data types IN NO WAY AFFECTS CODE SIZE. Sorry to say it loudly but too many people here keep repeating that.

    It may *appear* that way when working with STL but that is only because of the debugging information. Using templates will increase the amount of debug information in the executable (for each instance of the template) but it does not increase code size in any noticable manner.
    Exactly right. For my Thesis at University, my partner and I wrote a terminal program (think HyperTerminal) which supported both modems and packet radio, using g++ 2.95 and gtkmm (which makes extensive use of the STL). IIRC, code size was somewhere around 10k lines. With debugging info, the executable was a couple of megs. Without debugging, it dropped to ~100KB.
  94. STLport works with both MSVC and Embedded MSVC by cpeterso · · Score: 2

    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..

    1. Re:STLport works with both MSVC and Embedded MSVC by Jay+L · · Score: 2

      I once spent a month trying to get STLPort to compile on a Solaris 7 box with gcc 2.97. Never did get it working, and got no help from stlport.org either.

  95. Re:Why is inheriting from an STL class such a bad by lkaos · · Score: 2

    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));
  96. Error messages can be made readable by fitzsimj · · Score: 3, Informative

    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.

  97. STL is only as good as you... by jvl001 · · Score: 3, Informative
    I've been using the STL extensively in a multiplatform environment for the past 5 years, and I heartily recommend it. It certainly beats rolling your own, and execution speed is typically not an issue. Most of the pitfalls mentioned here are common to C++ in general. They can be summarized as follows:

    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.

    --
    /. is to journalism as graffiti is to a bathroom wall
  98. RougeWave? by jbayes · · Score: 2, Funny
    I'm a developer for a small software group that will soon migrate from using Rouge Wave to using the C++ STL.

    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

  99. Re:Why is inheriting from an STL class such a bad by hawkestein · · Score: 2

    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?
  100. The STL is not OO by Anonymous+Brave+Guy · · Score: 4, Insightful

    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.
    1. Re:The STL is not OO by Anonymous+Brave+Guy · · Score: 2

      True, but it's using parametric polymorphism, rather than classical OO "derived from a common base, is-a-type-of, shared interface" polymorphism, hence my note in the parent post. Also, note that common interface != polymorphism, necessarily.

      --
      If you disagree, post your argument. (-1, Overrated) isn't your personal censorship tool for views you don't like.
    2. Re:The STL is not OO by Anonymous+Brave+Guy · · Score: 2

      You're confusing the C++ standard library (of which the IOStreams library is a part) with the STL (which is a framework of containers, algorithms and iterators designed mostly by Alex Stepanov, and which is modelled by other parts of the C++ standard library).

      --
      If you disagree, post your argument. (-1, Overrated) isn't your personal censorship tool for views you don't like.
  101. old compilers. need for ref. counting, threading by prasad · · Score: 2, Informative

    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

  102. Re:Why is inheriting from an STL class such a bad by hawkestein · · Score: 2


    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?
  103. Re:maybe because MS doesn't implement the standard by Dr.+Manhattan · · Score: 2
    Noboby implements the standard perfectly yet. We had trouble with a product our group inherited. STL all over the place, and porting it from Solaris to HP-UX was a hassle. The port to AIX was even harder. There was always some stupid little template somwhere that didn't do quite what the other guys did.

    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!
  104. Debugging by loudici · · Score: 2, Insightful

    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
  105. Re:About maps... by JanneM · · Score: 2

    Now, isn't the point of encapsulation and abstraction that you don't need to care about the underlying implementation? Having a library where you need to (for all non-trivial applications) just defeats the purpose of all that complexity in the first place.

    /Janne

    --
    Trust the Computer. The Computer is your friend.
  106. Downsides by Frobnicator · · Score: 5, Interesting
    This is a longer post and has taken a while. Someone might have already said this, so please don't mod me as 'redundant'.

    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
  107. One example by Anonymous+Brave+Guy · · Score: 3, Informative

    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.
    1. Re:One example by Skapare · · Score: 2

      Read my reply to the next peer reply. I meant to reply to this one, but accidentally replied to the next one, even though it was the very same point. Even though a language does have some warts (things to be avoided) doesn't mean we have to characterize a language on the basis of being required to use all those warts. I'd never use qsort except in a pinch. And since I've developed other things to use instead, it's never going to even happen, anyway. Any language is what you make of it. C can be a very powerful language. But you'd never know that if you compared the code of an experienced C++ programmer against the code of a beginning C programmer. There being very few programmers quite experienced in both, this makes it hard to realize (I'm not one of them, as my experience does not include C++).

      I'm sure many people have dug up bad points about C++. But if those are things that good programmers avoid doing, then it doesn't merit saying that the language is bad for good programming by good programmers.

      One general flaw I have found in many newer languages is that they allow, or attract, a great many beginners, and even more people who should really never have been programmers at all. They produce horrible code in any language, but can actually get something accomplished (even though not very good) in a small subset of a higher level language. Then we have bad examples that don't even meet the original specifications passing themselves off as implementations.

      --
      now we need to go OSS in diesel cars
    2. Re:One example by dvdeug · · Score: 2

      One general flaw I have found in many newer languages is that they allow, or attract, a great many beginners, and even more people who should really never have been programmers at all.

      Yes! They never should have created Fortran; look at all the hacks who never should have been programmers who are programmers. If we'd stuck with assembly language, we wouldn't have this problem.

  108. er... "horseshit" by IBitOBear · · Score: 3, Flamebait

    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
    1. Re:er... "horseshit" by IBitOBear · · Score: 5, Informative

      Why it is a well-designed language:

      (Summary first) Everything was put in or left out for a reason and that reason (per thing) is documented if you take the time to look. Since it will be impossible in this forum to address the entirity of the issue I will stick to the elementes you named. Specifically the four casting operators (actually there are five) and the constructor invocation as a sixth "cast", which you incorrectly classify as an ambiguity.

      First you must consider the base language construct of the unconditional cast.

      struct A { ... };
      struct B { ... };

      A * ptr_to_A = new A();
      B * ptr_to_B = (B*)A;

      In the base language "C" the above is legal, will compile just fine, and is totaly wrong. This program would likely fail catostrophically. This is the generic version of an actual problem we (at my company) just found in a comercial "C" product.

      The thing is, the C-style cast has some core functionality that is occasionally indespensible. (The discussion of when and how this is indespensible is ommited as whole chapters of books cover this topic.)

      More importantly the C-style cast is a "gloves off" operation. When the programmer performs this basic operations it is with the understanding that if it is wrong it is to be done anyway. Complaining about its existence is like compalining to a surgon that a scalpel is dangerous because it could cut something...

      The four "lesser casts" (my term) are "gloves on" operations. The programmer, in using the spesific casts is describing a desireable transformation on the data and the compiler and/or runtime checks the viability of the operations to ensure that they are completely legal.

      Consider first a language that will do silent uncasted transformations (C++ will do these in some spesific and well defined cases which I will get back to later)

      if you have "let SomeString = SomeInt" and the language allows this as a transformation (see awk, possibly Perl etc) it will "just do it." but the "it" is only vaguely defined. It is worse if "let SomeInt = SomeString" where there is no obvious guarantee that "SomeString" contains a useful representation of a candidate integer.

      Ok, so we can agree that the transformation of a datum from one intrinsic type to another is problematic. Composite types make this a composite problem. Now back to the casts...

      All the casts represent expressions in the true sense. The opperations are transformative just as unary minus or square_root are transformative. The original object and representation are unchanged but the address or constantness or the "invariant" are manipulated. And like any expression there may be temporary objects involved. Listed from most-checked and safe to least, the compile-time resolvable casts are:

      const_cast(existing_object) => the existing_object may only vary from the new_type by the addition or removal [usually removal] of the constantness.

      static_cast(existing_object) => the existing_object must have a defined pathway to becomming an object of the new_type. Usually this is done by one of two methods. The most common transforms the address of the object into the address of the part of the object that is of the new_type. The second method creates a temporary object of the new_type using the relevant information from the existing_object.

      reintrepret_cast(existing_object) => almost always a transition from pointer-to-existing_object to pointer-to-void or vice versa. The reintrepret cast is used to release the expression from the constraints of the invariant of an object. Usually in order to pass the object through some external interface (e.g. passing it to the OS etc).

      Notice that these three casts each have a spesific guarantee of function for form. To take the safe root through a transformation you sometimes need to use two casts together. Most commonly you will un-constant-ize something and then static cast it if you are doing these kinds of casts in a way that requires composition. I'll skip the example for now. The important thing is that you can, once you know how to use your tools, know in turn exactly the transformations that your existing_object or reference or pointer there-to will undergo.

      There is no uncertanty in the three compile_time casts.

      The fourth "limited cast" is:

      dynamic_cast(existing_object)

      This one is trickeir as it has an implicit "if" statement within it at compile time and another "if" statement in it at runtime.

      IF new_type is an obvious part of existing_object the dynamic_cast is identical to the static_cast and you should have used that. The compiler will use that static_cast in place of the dynamic_cast because it knwos you are being dumb. 8-)

      IF however new_type is not clearly in existing_object(s) ancestory (this is the "else" of the above case) then the compiler generates code to deal wiht the cast at runtime instead of compile time.

      At runtime, IF the new_type object that is "part of" the "whole_object" that existing_object might also just be "part of" then the whole thing goes off without a hitch and the expression works. If the request is impossible then either a zero is returned (remember "transformative expression" 8-) or an exception is thrown. (the causes and cases are again ommited, go read the book).

      SO BACK TO THE CORE QUESTION: Why is the above a "good language design"?

      Answer: Because an unconditional cast "(new_type)existing_object" could do any combination of the above, but the above only happen explicitly if you use them explicitly.

      Hua?

      Well, in the first three you *ALWAYS* get a thing of the type new_type so there is no testing to be done. The compiler will not let the activity go wrong. You don't have to test anything in the code, the compiler makes you a warrent.

      The fourth, more dangerous and occasionally indispenseable and often quite desireable, cast needs support code.

      In a lesser language, I would either have to inclde the support code for every cast *OR* "work without a net".

      In C++ I can code to the spesific requirements.

      A language that lets the programmer code to the spesific requrements without having to put in lots of dead code just to be safe is "well designed".

      Some languages "seem" to be better designed because they put in the general case safety-net for you, but languages that generate "general case" code "for you" arn't well designed. The fact that some environments/compilers then try to take the safety-net code back out durring optimization etc are arguable. The work for the slapdash at the cost of allowing the programmer to express himself explicitly. When the programmer isn't really in charge of the code that is generally a "bad design" where effeciency is a factor. But for the people who need this net or don't know how to work without it, this kind of code is "good".

      But I digress.

      So what about the so-called "ambiguities" over constructor invocation as a casting operation.

      First, construction of a new object isn't, strictly speaking, a cast operation. It is "so like a cast operation" that in practical terms the two operations are considered synonymous.

      In actual fact, construction is construction. Casting is casting. Construction is the building of a new object using the information from zero or more old objects. Casting is the reconsideration of an existing object "in place".

      The confustion arrises because a sloppy thinker often cannot separate the classification of an object from the application of the value of that object.

      In the expression "A = B;" A is being transformed. In the special case "A_Type A = B;" the transformation of "starts from nothing". The construction of paramter objects durring fuction call is the latter case.

      The language allows us to define the transformation of A with respect to many types. If we create a transformation of A based on a B then this is obvious. Sometimes things are not that simple.

      The programmer is allowd to make a chain of transformations implicit in ther code space because the language design allows for one "free and silent" step to be added. That is, if B can become X and X may be used to transform A, then B will transform A by way of a temporary X.

      The user is spesifically warned that this feature must be used wiht due dilligence. In particular if there is more than one possible X intermediary the compiler will pick the "best" one. The rules for finding this "best X" are explicit (there are exactly four such rules).

      Additionally, under no circumstances will B => Y => X => A considered.

      If there is more than one "X" and they score the same on the "betsness" scale the compiler will demand the programmer clean up his mess. Many less-well designed languages will silently pick one wihtout a peep, which one may change from compile to compile. This would be an inferior design because any "X" may have larger-scale implications.

      The educated user is capible of making the transformations work seamlessly.

      The educated user is capible of explicitly disallowing some transformations by use of the keyword "explicit".

      The uneducated user is going to make a mess if he fails to understand and use the feature.

      There is absolutely no ambiguity.

      The fact of the matter is that a poor design will net poor code. Some languages will glop out corrective code for the programmer. Where the programmer is willing to pay this expense, and the application can afford this expense the issue is a giant "don't care".

      Where the cost should not be paid, the "looser" languages don't give the programmer the ability to remove these expenses. To that end these "looser" languages have an intrinsic limit to their functionality.

      Every language does actually.

      However proficency in the tighter (and more demanding) language translates directly into the skillset needed for a looser language. The converse isn't true.

      There is an old aphorisim: "If all you have is a hammer every problem looks like a nail." The secret obverse is "the more tools you have the easier it is to find the right tool for the job."

      Think nailgun. Heavy, dangerous, effective as hell. If you are competent to use one, it will serve you well. If you never learned to use anthing more invasive than wood-glue then don't pelase-god try to use the nailgun.

      The fact that you are uncomfortable using a nailgun doesn't intrinisicly mean the nailgun is poorly designed.

      It's a poor craftsman that blames the tools.

      --
      Innocent people shouldn't be forced to pay for inferior software development.
      --"Code Complete" Microsoft Press
    2. Re:er... "horseshit" by jejones · · Score: 2
      Wow...that's quite the non sequitur. There are other reasons to choose C or C++ to write a program in, e.g. portability.

      Isn't it about time to retire that old rationalization for needlessly complicated or error-prone programming languages: "Professional tools are necessarily complicated and easy to put out your eye/cut your arm off with," with the subtext of "I'm an 3L337 D00D because I {know all the IEYxxxx error codes in OS/360, never need cdecl, know all the perverse interactions of obscure C++ features}."

    3. Re:er... "horseshit" by ajs · · Score: 3, Insightful
      And I quote:
      "Everything was put in or left out for a reason and that reason (per thing) is documented if you take the time to look" [...] "In the base language "C" the above is legal, will compile just fine, and is totaly wrong."
      Not every C++ devotee suffers from this sort of viewpoint, but many do, so I'd like to address it first. The idea that everything exists in a language for a well-defined, unique reason is hardly a defense of the language DESIGN. Yes, there are four casting operators because the designers felt that each was justified. In a truely high-level language you would only need one, and it would rely on the nature of the data to "do the right thing. In a truely low-level language you would need only one and it would do what you told it to, even if it was the wrong thing.

      C does not attempt to prevent the problem that you cite above. C++ doesn't either, it just gives you a way, assuming you understand the language completely to ask the compiler to make it harder. This adds many layers of complexity and provides you with the situation where the vast majority of C++ programmers continue to use the C-style cast.

      "The thing is, the C-style cast has some core functionality that is occasionally indespensible. (The discussion of when and how this is indespensible is ommited as whole chapters of books cover this topic.)"
      Shouldn't your language be simple enough that those books aren't necessary, just to explain a core feature? Shouldn't your compiler either do the work of resolving your complex relationships or get the heck out of your way?

      I look at any large-scale C++ project and I see something that Perl has classically suffered from too: there's more than one way to do it, and no one agrees on which way that is. In Perl, it's considered a strength because the language is so forgiving that it resolves many of the problems created this way (Python by contrast allows you to do things exactly the way Guido wants you to, and that too can work well). C++ however, does not give you any sort of assistance in resolving these problems, and differing views on which language is being used can be catastrophic.

      This is, in fact, one of the reasons that Effective C++ and More Effective C++ should be required reading for every member of any C++ project. It's not that you'll get good ideas, but the fact that those books teach a certain dialect of C++, and gently bludgen the reader into accepting that that dialect *is* C++. The STL also does this by formalizing a dialect of C++ into a library that insinuates itself into your code (I never saw people using functors until STL became wide-spread, and then people felt they had to use them).

      C also requires that you adopt some common usage, but the advantage there is that C is so painfully simple that it is hard to adopt a dialect that is wildly out of step with other programmers (I've seen people use cpp to prove me wrong here, and all I can say is cpp is perhaps the worst idea to ever grace a language).

      C++ is a very good accedemic exploration of the value of C as a high-level language. It's ultimately a poor choice for real-world programming, but that may not have been an obvious conclusion if Mr. Stroustrup had not been so bold. I don't question the genius of the ideas behind the language, just the danger of using it on a daily basis.

    4. Re:er... "horseshit" by elflord · · Score: 2
      The idea that everything exists in a language for a well-defined, unique reason is hardly a defense of the language DESIGN

      The fact that there exists a well reasoned explanation of why these things exist most certainly is a convincing defense.

      In a truely high-level language you would only need one, and it would rely on the nature of the data to "do the right thing. In a truely low-level language you would need only one and it would do what you told it to, even if it was the wrong thing.

      Yawn! See "false dichotomy". C++ is was not designed to be "truly high level", or "truly low level". It's designed to solve real world problems, often at the expense of abstract notions of truth and beauty.

      C++ doesn't either, it just gives you a way, assuming you understand the language completely to ask the compiler to make it harder. This adds many layers of complexity and provides you with the situation where the vast majority of C++ programmers continue to use the C-style cast.

      (Shrug) C++ is designed to be compatible with C. There are good reasons for this choice, and IMO the vast popularity of C++ is largely because of C compatibility. The fact that a lot of compilers use C-style casts is a reflection of this too- they use it because they are familiar with C.

      Shouldn't your language be simple enough that those books aren't necessary, just to explain a core feature? Shouldn't your compiler either do the work of resolving your complex relationships or get the heck out of your way?

      There are a lot of properties "your language" "should" have, and no language has all of them. So you have to choose. C++ was not designed for abstract beauty. It was not designed for language masturbators. It was designed for people who need to solve real world problems. Simplicity and abstract beauty are not terribly good predictors of the success a language will have at solving real problems.

      In Perl, it's considered a strength because the language is so forgiving that it resolves many of the problems created this way

      Horseshit. Perl lacks static type checking, which means that it's very easy to put subtle bugs in code, because of type errors (esp with numeric vs string types) C++ catches this sort of thing at compile time, and in fact with template types, it arguably has a better static checking mechanism than any other popular programming language.

      C also requires that you adopt some common usage, but the advantage there is that C is so painfully simple that it is hard to adopt a dialect that is wildly out of step with other programmers

      Not at all. Consider the GTK+ object model (which is basically C++ on top of C), compared with more dynamic object models that can also be implemented in C. Consider the millions of different ways one can emulate parametrised types in C. C is only simple if you don't try to do very much with it. The moment you start needing associative containers, functors, and polymorphism, it gets very complex very quickly. Consider this-- how many different ways are there to do object oriented programming in C, and how many in C++ ? C++ provides an object model using well-defined semantics, while to use objects in C, you need to use your choice of idiosyncratic hack.

      The other problem with your reasoning is the implicit assumption that a line of code is the level at which a human comprehends code. In practice, one reads code one function at a time. So having a simpler language isn't much help if the resulting functions have deeper nesting (eg switch vs polymorphism), longer parameter lists, and more lines of code.

      C++ is a very good accedemic exploration of the value of C as a high-level language. It's ultimately a poor choice for real-world programming,

      Hahahahaha ... Academic ??? You're talking about what is arguably the most succesful language for developing useful real world applications. Here's a free clue-- your abstract notions oof "truth", "beauty", and "purity" don't mean sh*t when it comes to "real-world programming".

  109. hey! lay off Java by Sanity · · Score: 2
    Java has only some of C's problems while being totally platform-antisocial (platform neutral would imply that it plays nicely with all platforms which is patently untrue).
    Sun's JRE implementation, in my experience, is pretty solid on both Linux and Windows (the only platforms on which I have tested it). Kaffe, when they release the next version (1.0.6 is ancient) will provide a pretty solid Open Source JRE, IBMs JRE is pretty good provided you don't want to do anything rediculously complex (we have run into some really obscure bugs with it). no JRE is perfectly bug-free (what software is?), but they are pretty solid, and improving every day. To describe Java as "totally platform-antisocial" betrays an anti-Java bias on your part.
    I will say that Java has one of the best object models of any language out there, but 1) that will change when Perl6 hits the streets
    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.
    and 2) it's somewhat overshadowed by the failure of the Java libraries to live up to the promise.
    As an experienced Java developer, I have never really felt disappointed by the Java libraries (with the sole exception of the lack of support for asynchronous networking until 1.4) - what exactly is your beef with them?
  110. The biggest advantage by Arandir · · Score: 2

    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
  111. The age of C++ by Anonymous+Brave+Guy · · Score: 2
    The standard (or rather, this standard) may be young, but the only way to refer to C++ as a young language is to compare it with the lifetime of the universe.

    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.
  112. Actually... by petis · · Score: 2

    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.

  113. More readable by Jay+L · · Score: 2

    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...

  114. Well, based on my experience with it.. by Rob+Kaper · · Score: 2

    ..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.

  115. Re:STL Downsides? by Tattva · · Score: 2
    That's a pretty broad statement, and again I disagree. Suposing you want to create a string class with a subset of the functionality in std::string? Do you re-implement it? Supposing you want to create a structure that is best expressed as a list, but has just a little more functionality? Granted, you have to keep a pointer to the derived class, because of the virtual dtor issue, but its not completely unheard of.

    I disagree with your disagreement. Ask yourself this: why do I want to derive from the string class? Is it because you have a new function you will be adding and every other string method is still necessary for your derived class? Since string has methods for several diffent uses, it is unlikely you actually need everything that it implements, and creating a new class with that broad set of functionality (via inheritence) is bad programming practice because you have given your class more functionality than it needs. This is even more true for a list class. I'm sorry, but I can't imagine a situation where every single list method is required.

    Just create a new class with the same methods that you needed from the old class and add the new ones to it. You can also put in copy constructors and conversion operators that allow interoperation between your new string class and the old one easily enough.

    After all, did the designers of STL say, "boy, we like this vector class, let's derive a list class off of it to save some work"? Nope, they reimplemented using many of the same method names and styles since they didn't need polymorphism between the two classes, just mental model-sharing.

    --
    personal attacks hurt, especially when deserved
  116. Re:hey! lay off Java by ajs · · Score: 3, Insightful
    You said:
    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.
    First, define "scirpting language". When the term was coined it refered to syntax-heavy, grammar-light "languages" like bourne shell whose basic purpose was to collect commands into a re-executable, sequential file.

    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.
    As an experienced Java developer, I have never really felt disappointed by the Java libraries (with the sole exception of the lack of support for asynchronous networking until 1.4) - what exactly is your beef with them?
    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.
  117. I like java. by rebelcool · · Score: 2
    Java is my most often used language. I haven't actually used the STL in a year or so..only I remember the horrors of debugging it.

    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.

    --

    -

    1. Re:I like java. by ahde · · Score: 2

      C# takes the syntax of java and combines it with the runtime of java. There are some win32 libraries added that Sun didn't appreciate when Microsoft tried including them with J++. Oh, and they changed System.out.println() to System.console.writeln().

  118. Re:Not all compilers support it, god-awful comp er by wurp · · Score: 2

    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.

  119. Speaking from experience... by jschmerge · · Score: 2, Interesting

    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:

    • An uncaught exception results in a core dump
    • A Standards compliant version of the STL must throw exceptions (it's part of the standard)
    • Usually exception handling is a feature neglected during the design of a large system's architecture, primarily due to people's lack of experience with C++
    • Wily-Nily exception handling results in a very messy architecture

    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:

    class Base
    {
    ...
    };

    class Derived : public Base
    {
    ...
    };

    Base b;
    Derived d;
    std::vector<Base> v;

    v.push_back(b);
    v.push_back(d);

    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 string class that is almost part of the STL should be avoided. It is extremely inefficient to use, does not implement reference counting, and will generally cause many more problems than it is worth.
    • Several assemblers (most notably older versions of Solaris's) have problems with the extremely long function names that get generated by the mangling process.
    • Learn the functions/functors provided in <algorithm>
    • Life can be a lot simpler if you make a habit of qualifying STL functions with their namespace (i.e. prefixing names with 'std::' instead of relying on the global 'using std;' directive).
    • A compiler that supports the export keyword may help bring code size down.
    • Remember that there is no compiler in existence that actually implements the C++ standard correctly... Being proactive in this regard can sometimes save a lot of agravation if a time comes that you need to port your application to new platforms.
    • While the STL is extremely efficient at generic algorithms, hand-written code generally is leaner and faster.
    • If working as part of a large team, take the time to educate people on how to use the STL, so the code doesn't seem foriegn to them.
    • Always pass containers by reference or const-reference.

    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.

    1. Re:Speaking from experience... by elflord · · Score: 2
      The string class that is almost part of the STL should be avoided. It is extremely inefficient to use, does not implement reference counting, and will generally cause many more problems than it is worth.

      Actually, it's worse than this. Whether or not string uses reference counting is unspecified. As Austern notes, the trend is that COW reference counted implementations are falling out of favor. The fact that this is ambiguous is in itself a reason not to use std::string if performance matters.

      It's worth mentioining that COW reference counted classes are actually a performance liability, because of the overhead incurred by checking when references are handed out (and because you can't give references out without forcing a deep copy). A better reference counted model would be an immutable reference counted string.

      compiler that supports the export keyword may help bring code size down

      Too bad such a compiler doesn't exist. There are other approaches though--implicit instantiation. Or compilers that are smart enough to collapse multiple instances.

  120. Great algorithms, but hard to take advantage by Anonymous+Brave+Guy · · Score: 2

    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.
  121. Re:About maps... by J.Random+Hacker · · Score: 2

    Actually, the sorted containers are implemented using red-black trees. Hash tables are not used in the sorted containers because the performance of a hash function can't be guaranteed.

    Iterating over the leaf nodes is the same cost as iterating over a list. Finding an element with a known key value is logN for the sorted containers while the same operation in a list is linear.

  122. Re:Not all compilers support it, god-awful comp er by Panaflex · · Score: 2

    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.
  123. /. is a skewed sample by LoveMe2Times · · Score: 5, Informative

    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.

  124. Re:Not all compilers support it, god-awful comp er by Daniel · · Score: 2

    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!
  125. Performance & size tests, c, gcc & stlport by james_northrup · · Score: 4, Informative
    I have been held to the java grindstone for 7 years and growing steadily despondant wishing I were back designing swift running systems of elegant templates... so this weekend I sat down for a personal STL refresher.

    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.

  126. Re:STL Downsides? by Tony+Hoyle · · Score: 2

    Deriving from string is perfectly valid, although it's better to derive from basic_string which is what a string is anyway...

    For example, we have a string class that add a 'printf' member function. The other way to do it would be to have a global function that takes a string, which is a far worse option.

    What about the need for an 'exists' function in map classes? Sure, you can do it in a couple of lines of STL but if you've got 1000 of those then it gets real tedious. Simply derive a new map and use that & problem solved.

  127. Re:Team work by Tony+Hoyle · · Score: 2

    The STL *is* part of the C++ language.

    Anyone claiming to know C++ who doesn't know the STL is lying.

  128. Solving C++ template code bloat with Squeeze++ by brdsutte · · Score: 4, Informative
    Code bloat need not be a problem of using templates. If you look at

    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

  129. Re:hey! lay off Java by Sanity · · Score: 2
    First, define "scirpting language".
    Well, that is an impossible task to do perfectly, but basically I think it is partially the degree to which languages are compiled before deployment. C++ is totally complied, Java is compiled to a low-level bytecode, I doubt Perl is compiled to even nearly the same degree. There are other indicators, such as strict type-checking that tend to be lacking in scripting languages such as Perl and Python. Also, the history of Perl betrays its true nature, it was designed for text-processing. This is still more than visible in its design today. Perl may have aquired the trappings of a real programming language, but its true nature is still that of an "awk" replacement.
    If you've ignored Perl because it looks scary, go back and try it again.
    I have ignored Perl because I was once forced to maintain someone else's Perl code, and still have the scars. Even well-written Perl code can be intimidating to maintain, and IMHO a good language should place limits on how badly code can be written, Perl seems to pride itself in not having any such limits.
    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!
    My idea of the perfect standard library isn't one that has specialized functions for everything under the sun - that is just bloat. A good library should provide effective building blocks, but not try to do everything.
  130. Re:About maps... by coyote-san · · Score: 2

    Close. The goal with abstraction is that you can usually swap one object for another with a single change to the source file. You shouldn't have to make any other changes in the source code. You choose the object precisely because of the different costs of different types of operations.

    This is much clearer in Java than in C++, since the interface is distinct from the class that implements it. E.g., in Java I can specify that I want a "SortedSet" interface (which describes the operations that are valid on the object - and which isn't easily changed), and the constructor specifies that I want it actually implemented with a "TreeSet."

    --
    For every complex problem there is an answer that is clear, simple, and wrong. -- H L Mencken
  131. Re:Templates can get really, really, really ugly. by ConceptJunkie · · Score: 2

    I've never seen a library of any kind that couldn't be used hard without eventually having to look at (or wishing you could look at) the source. Since the source for STL isn't comprehendable by anyone short of the people who wrote it (perhaps not even them), I would be very reluctant to use it.

    In fact, I have been working for over a year on a project that I didn't write that is part in VC++ and part in Borland C++ (don't ask), and STL has been a real headache for me.

    As long as it works, I'm fine, but debugging it, and sometimes even working out the header file dependancies is horrible.

    I'm of the category of folks who uses a home-grown container library that is easier to use and more consistent than STL, at the expense of some flexibility, some performance, and a whole lotta obfuscation.

    And yes, I use macros in a templatey way, but it's totally portable, has full type checking and is reasonable to debug.

    My advise is take some non-trivial time to educate yourself or you may make a decision (for or against) that you will come to regret later.

    --
    You are in a maze of twisty little passages, all alike.
  132. Re:About maps... by gkatsi · · Score: 2

    Well, you don't care about the implementation. But you do care what kind of operation you are performing. You don't really want to "encapsulate" away that you will perform a linear time lookup instead of log-time lookup when you use a list versus a set.

    Think of them as different operations that one container supports and the other does not.

  133. RWTools vs. STL by KC0A · · Score: 2, Informative

    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.

  134. Re:STL Downsides? by HopeOS · · Score: 2, Insightful
    C++ templates are one of the best features of the language...

    They are no different than a majority of languages out there...

    ...regarding templates being created at compile-time as being a bad thing. That's what generic programming is all about!!!

    No sir. Generics should be resolved at run-time as much as possible...
    C++ is an extension of C; its primary objective was to provide aspects of object-oriented programming to C. Both C and C++ compile to assembly at very-nearly a 1:1 basis. This makes both very fast, with virtual functions being only slightly slower. There is little to no runtime information provided as these are features of higher-level languages which are formulated around support for late-binding. Use the correct tool for the job.

    Call the wrong function name in java or python and you get a runtime exception; call the wrong function in C++ you get a compile-time error. The difference in these two methodologies translates to raw execution speed. RTTI is underutilized in C++ because it's largely unnecessary and facilitates breaking the strong-data-type model. This model is what makes C and C++ so fast; it provides immediate function linkage with no time-consuming function lookup or indirection.

    As with all languages- show me the code -- the final assembly code. I am very impressed with how well templated code is inlined, optimized, and scheduled on multiple-pipeline processors. After stripping the symbols from the executable, I don't detect any appreciable code bloat inconsistent with the increase in speed I received by inlining my collection classes. Even MSVC6 can do this.
    I'd love to hear an example of a language that implements some kind of generic stuff at runtime.

    Smalltalk, Python, Dynace, Objective-C and even C... all nice languages
    With the exception of C (and possibly ObjC), all the languages listed use runtime function-name/prototype to function-code binding which is nowhere near as efficient as C or C++'s compile-time function linking. Your mention of C is either erroneous, or you are referring simply to collection classes of opaque data. This is hardly an improvement over the existing options- particularly since it completely circumvents the strong-type model already available with C and C++.

    It makes absolutely no difference at runtime.

    I beg to differ. *every* template you instantiate adds to the binary size because of the need to use them. If I create a vector<string> and vector<int> I get *two* vector class and it will increase the binary size accordingly. Another downfall is that you can't mix and match types, so you have to encapsulate your nodes in yet *another* class... adding even more to the binary.
    This is a serious stretch of the truth. Every template you instantiate will increase the size of the code- by the size of the vector constructor code- which is usually a dozen or so bytes at most. Only the functions actually used are included in the code- not every function in the template. Most functions are inlined so you can fully expect those to increase the size of the code while providing an increase in execution speed. The typical functions like begin, end, and iterator increment while typically resolve to a single assembly instruction- less than the equivalent function call to a general collection class!

    If you create a vector<string> and a vector<int> you will get two completely different sets of code. The vector<int> will not attempt to call constructors for your int's and can ultimately use an assembly-level memcpy to transfer the contents. The vector<string> will call the constructor and/or copy-constructor of every string you add, which is fine since that's what you want. Two completely different implementations for two completely different types- both optimized for their respective characteristics. No runtime vector implementation is going to provide that, period. You will always get worst-case implementation for both int's and string's because strings necessitate special handling for construction, copying, and deconstruction. At runtime, you get the same poor performance for your int's that you do for your strings.
    As for mixing strings and int's in a vector... why? Performance considerations must be weighed against implementation. If mixing int's with strings substantially increases the cost of using the vector, there had better be a really good reason. The first reason might be that execution time is less critical than coding time, in which case, you're probably not using the correct language anyway. Java or python might be more appropriate. Again, use the right tool for the job. As far as I'm concerned, mixing types as you described is a recipe for distaster as it substantially increases the complexity of auditing the code in the future. If I'm enumerating this vector, how can I guarantee that I'm not going to find some other data type in there? Do I throw an exception or try to convert to an int? Or should I convert to a string instead?

    C++ is a young language with a young standard.

    Even more reason not to use it!! the STL is *not* standardized, check your implementations.
    It's being used, standard or no standard, because the utility of the language exceeds the cost of failing to compile properly on all target platforms. Implementations which fail to compile properly can be remedied, as necessary, on the build target. Field fixes are common in cross-compilation, nothing to see here, move along.
    YOU SHOULD NEVER INHERENT FROM AN STL CONTAINER. Period.

    I disagree. You want to extend an STL containter to create better ones.
    I couldn't care less if someone derives from an STL container or not. The risks are clearly stated, possibly even overrated. I've found that inheriting directly from a container without declaring the new class as a template itself usually leads to confusion later. A private member variable tends to be more effective. Once you leave the realm of "general template" and enter the realm of "implementation", it makes sense to hide the collection class. Who knows, you may decide to dump the STL class for another class later. If the code which relies on your class breaks when this happens, you've done a poor job at object-oriented programming. Plus, this solves the multiple inheritance problem mentioned by another poster since your new aggregating object can have any baseclass it wants.

    For instance??? You are doing yourself an extreme disservice by avoiding STL.

    hmm.. wxWindows, QT, Gtk+, Plib, and any other library that wishes to be *portable*. IMO, you do yourself a great disservice for using the STL.
    Assuming you are compiling with gcc, which covers a considerable number of platforms, just how less portable are you realistically going to be? MSVC does a fair job- ATL COM is built entirely on templates (for better or worse, although their primary objective was reduced code size for ActiveX components- templates where largely responsible for this).

    I was a skeptic of templates for a long time until I examined the compilation process at an assembly-language level. Sold! Now I use them daily. The time savings is simply beyond belief. I'll never implement a red-black binary tree again. What a template does for general programming is nothing short of exciting- try looking at difference between the assembly generated by vector<string> and vector<int> sometime- it's inspirational!

    -Hope
  135. Re:er... "horseshit" (http-ed again) by IBitOBear · · Score: 2, Informative

    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
  136. Re:Not all compilers support it, god-awful comp er by nihilogos · · Score: 2

    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
  137. Lisp: the Meta-Programming Shangra-Language by SimHacker · · Score: 2, Interesting
    The Meta-Programming Shangra-Language for which you yearn has been around for many years, and it's called Lisp.

    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
  138. Re:Why is inheriting from an STL class such a bad by lkaos · · Score: 2

    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));
  139. Re:STL Downsides? by lkaos · · Score: 2

    Deriving from string is perfectly valid, although it's better to derive from basic_string which is what a string is anyway...

    It is absolutely not valid! The string (and basic_string) class does not have a virtual destructor. If your new class is deleted via a pointer to the base class, undefined behavior will result. That is right, the behavior is undefined (although usually your subclasses destructor is just not called).

    Very, very bad thing.

    Why is it bad to have a function that takes a string???

    Better than having undefined behavior IMVHO.

    --
    int func(int a);
    func((b += 3, b));
  140. Re:hey! lay off Java by aminorex · · Score: 2

    > 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-
  141. Downside by BigLinuxGuy · · Score: 2, Insightful

    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.....

  142. Re:err, tabs aren't an issue by ahde · · Score: 2

    ah, business functionality.

    That's the point. "Programming" is more than just string comparison and arithmatic.

  143. Re:Peformence by tommck · · Score: 2

    So, what's the problem with the STL string?

    --
    ---- It puts the lotion on its skin or else it gets the hose again. It does this whenever it's told.
  144. Apples... Oranges... by tommck · · Score: 2
    You said "use the STL algorithms only if you don't care about performance".

    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.
    1. Re:Apples... Oranges... by Jay+L · · Score: 2

      You said "use the STL algorithms only if you don't care about performance". Now, you are backing that up by saying that the "string" class is slow.

      And if it were I that had said the former, you would have successfully poked a hole in my argument.

    2. Re:Apples... Oranges... by tommck · · Score: 2
      Ok, let me rephrase: (i.e. s/You/The original poster/)

      The original poster said "use the STL algorithms only if you don't care about performance". Now, you are backing that up by saying that the "string" class is slow.

      We still have the same problem. You were not following the "thread" of the conversation, you were deflecting it to another issue. Thus, your post is off-topic for this thread of the conversation. Your point was valid, just not as a reply to my post.

      T

      --
      ---- It puts the lotion on its skin or else it gets the hose again. It does this whenever it's told.
    3. Re:Apples... Oranges... by Jay+L · · Score: 2

      You were not following the "thread" of the conversation, you were deflecting it to another issue.

      You are right. I remembered some discussion about algorithms, but I thought the post I replied to (yours) was discussing the speed of the STL in general - in fact, it was of course discussing the algorithms as well. My bad.

    4. Re:Apples... Oranges... by tommck · · Score: 2
      No big deal. I am actually curious what kinds of things were being done with the strings that made it slow. Of course, things can always be optimized for speed. I'm wondering if the code was just allowing strings to allocate it's pre-determined buffer and grow itself (read: many reallocations and assignments) or whether there was an attempt to optimize within the confines of the STL.

      T

      --
      ---- It puts the lotion on its skin or else it gets the hose again. It does this whenever it's told.
    5. Re:Apples... Oranges... by Jay+L · · Score: 2

      I am actually curious what kinds of things were being done with the strings that made it slow.

      If I knew, I forgot...

  145. Re:STL Downsides? by Jherico · · Score: 2
    Since string has methods for several diffent uses, it is unlikely you actually need everything that it implements, and creating a new class with that broad set of functionality (via inheritence) is bad programming practice because you have given your class more functionality than it needs.

    String in itself has more functionality than most people need. Most of the STL containers do for that matter. Part of the advantage to the STL is that as templates, only the parts you actually use are compiled into the program. If your derivation is in turn a template class as well, you retain this advantage. And even if your derived class is a specific type instance, the linker will remove uneeded code. If you argument applies not to code generation, but just the amount of functionality in the class, your complaint could just as easily be leveled against the whole of STL.

    As a good example, suppose your are migrating away from a custom string class, or something like MFC's CString. You can derive from std::string, and then implement compatibility functions as needed, expressing them in terms of the native std::string. This is an excellent first step in migrating away from even the usage of the non-standard functions, since you can now do that incrementally.

    Your example of list vs. vector is specious, because where functionality between the two overlaps, there are vastly different requirements in behaviour concerning speed of operations. If that is the case, then yes, you're better off implemnting a new class (or deriving from or containing an instance of the correct STL class).

    I grant you that the need for derivation is rare, and most places where it would be used could be as easily accomplished with generic functions that operate on your data structure instead of being a member of your derived class, but there are times when it is more effective to derive. Brad

    --

    Jherico

    What can the average user can do to ensure his security? "Nothing, you're screwed"

  146. Perl is like Duct Tape by kaladorn · · Score: 2

    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."
    1. Re:Perl is like Duct Tape by kaladorn · · Score: 2

      Yes, but I think disclosing them might leak information that (literally) impacts market value of several of these companies. So I'd best not be terribly specific. Let's just say I know folks building DSLAMs that tried putting together a lot of their architecture using Perl. It was good in some ways - got them 2 years of development in 6 months. But once deployed, stability/robustness/maintainability issues in both Perl and Linux caused them to eventually re-write in C/C+ and put them on Solaris platforms. Perl gave them fast development, a product to advertise, and some customers, then C/C++ offered them a long-term viability they weren't getting from the Perl code.

      --
      -- Mal: "Well they tell you: never hit a man with a closed fist. But it is, on occasion, hilarious."
  147. Speed over safety w/STL example code by CodeBuster · · Score: 2, Insightful

    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++);
    }

  148. Re:Debugging Problems by spitzak · · Score: 2

    I get these warnings all the time from VC++ but it seems they can be ignored. The programs link and run fine. I guess you can't use the symbols in the debugger, but I doubt that the 512-character symbol is really that useful in debugging anyway.

  149. Re:Yes Virginia, there are decent languages by aebrain · · Score: 2, Interesting
    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 =)

    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) :

    There is now compelling evidence that development methods that focus on bug prevention rather than bug detection can both raise quality and save time and money. A recent, large avionics project reported a four-fold productivity and 10-fold quality improvement by adopting such methods. A key ingredient of correctness by construction is the use of unambiguous programming languages that allow rigorous analysis very early in the development process.
    SPARK code was found to have only 10 percent of the residual errors of full Ada; Ada was found to have only 10 percent of the residual errors of code written in C. This is an interesting counter to those who maintain that choice of programming language does not matter, and that critical code can be written correctly in any language: The claim may be true in principle but clearly is not commonly achieved in practice. (emphasis added by me)

    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
  150. Re:Memory Management by plover · · Score: 2
    It sounds like it's too late, but if you check inside the header that came with your STL, you might find that you can define a flag that will alter the default allocator's behavior to something that suits your needs better.

    Obviously, telling you to grovel through someone else's template declarations isn't a particularily strong argument in favor of the STL, but it might solve your problem.

    --
    John
  151. Re:Not all compilers support it, god-awful comp er by ciole · · Score: 2

    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.

  152. Re:Not a standard reference implementation by be-fan · · Score: 2

    Actually, STLport is almost close to a standard implementation. It's extremely complient, high-quality, and free so you can use it wherever you need to.

    --
    A deep unwavering belief is a sure sign you're missing something...
  153. stl = big powerful juju by technoCon · · Score: 3, Interesting

    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.

    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 .NET components, C# and/or "managed C++."

    Or you could do Java. but i don't know how to do "generic programming" in Java.

  154. Look at boost by lpontiac · · Score: 2

    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

  155. Re:Not all compilers support it, god-awful comp er by wurp · · Score: 2

    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.

  156. STL Error Decrpyter by ElJefe · · Score: 3, Interesting

    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.

  157. C++ needs named parameters prhps by Tablizer · · Score: 2

    (* 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.

  158. Re:Not all compilers support it, god-awful comp er by Daniel · · Score: 2

    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!
  159. Brings out the worst in compilers... by Anonymous Coward · · Score: 2, Insightful

    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).

  160. Heh by autopr0n · · Score: 2

    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.
  161. Re:Not all compilers support it, god-awful comp er by leviramsey · · Score: 2

    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...

  162. Re:Java is even less standard though! by Tim+C · · Score: 2

    with the class documentation open in a web browser at all times since it's so hard to remember the inconsistent naming

    You really ought to get a decent IDE. A couple of reasonably good, free ones are AnyJ (http://netcomputing.de/), which is free as in beer for Linux but pay-for for Windows, and NetBeans (http://netbeans.org), which is free as in beer and speech (SPL, not GPL). (Standard disclaimer: I have nothing to do with either group or IDE, other products exist, etc)

    I'm assuming that you use a text editor for coding; trust me, once you've used an IDE with built in compilation and debug support, and a CodeInsight-like feature (which suggests possible completions for what you are typing, either automatically or on demand - no more having to have the docs open to remember what methods a class has!), you won't want to go back.

    The only downside is that, being pure-Java apps, you're going to have to have a reasonably beefy machine. JBuilder (commercial, expensive, what we use at work) performs adequately on a P3 450 with 384MB of RAM, most of the time.

  163. And it also goes to show you... by rjh · · Score: 2

    ... 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.

  164. Not OO, on purpose by sohp · · Score: 3, Interesting

    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.

  165. no hashmap by ttfkam · · Score: 2

    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.
  166. Re:In my experience... by BCoates · · Score: 2

    Some aspects of the STL can be overly constraining. I find it very unnatural to have to specify one and only one comparison operation that dictates the sort order of a vector. In C, if you want to sort things differently, you can hand a new function pointer to qsort(), but with the STL, you're kind of out of luck. How would you go about writing a (thread safe) program that allows the user to sort something according to run-time criteria?

    vector doesn't have a sort order, as it's not a sorted container, you can sort them at runtime with sort() or one of the other sorting algorithms.

    Containers like set need a sort order specified because they are kept an a sorted state all the time.

    --
    Benjamin Coates

  167. Re:STL Downsides? by Tony+Hoyle · · Score: 2

    It's bad to have a global function when you should be writing OO. The string object should know how to do a format operation on itself.

    The subclass needs no destructor anyway, since it's just extending the methods of a predefined class, not adding destructable properties to it.

    btw. The whole virtual destructor thing is a red herring. Unless your compiler is seriously broken it'll work fine (it certainly does in VC++) - each object knows what type it is & knows how to destroy itself.

  168. Re:C++ is a horrible OBJECT language. by muchandr · · Score: 2, Interesting

    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?

  169. Re:STL Downsides? by lkaos · · Score: 2

    Seriously, dude, take some time to actually learn all the cases, rather than just blindly quoting some overly-simplified rule that you read in some style guide.

    It's not being overly dramatic, this is coming from spending more than one late night debugging code because some entry level person who doesn't know what their doing didn't make their base classes destructor virtual.

    There's a lot of things I can do safely but would never even consider doing in a production environment because while *I* may know what not to do, I cannot guarentee that others will.

    --
    int func(int a);
    func((b += 3, b));
  170. *Rouge* Wave? by jdfox · · Score: 2


    That must be the San Francisco-based subsidiary of Rogue Wave, right? :-)

  171. Wishing Ourselves to Death by ChaoticCoyote · · Score: 3, Insightful

    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. ;)

    1. Re:Wishing Ourselves to Death by elflord · · Score: 2
      In my experience, C++ iterators, algorithms, and containers are inefficient and unnecessarily complex.

      In my experience, they're quite efficient if you compile with optimisation. YMMV. I disagree with "Unnecessarily complex", if the complexity was not necessary, they wouldn't be used.

      We need to refine the current standard before we begin adding new material;

      The problem is that refinements that remove functionality or otherwise break compatibility are impractical. At best we can deprecate features, but this doesn't mean a whole lot in practice.

      Some people argue that, for the sake of completeness, we should add hash-based containers to the standard library.

      I don't think "completeness" is a good reason in itself. The container needs to be useful to enough people to justify including it in a standard library. IMO, hash tables are borderline, given that we already have maps.

      someone might want balanced binary tree containers,

      We already do (set/multiset and map/multimap)

      And then we get into the whole issue of graphical development

      I don't see how this follows-- it's an enormous leap. Graphical development is inherently nonportable and platform dependent, generic containers are not. The closest we've come to providing platform functionality is in file I/O libraries (especially the C-based ones).

      Should a list be sorted via its member method or the sort algorithm?

      This is not an "inconsistency". The answer is consistently the same-- the member function should always be preferred over the non-member function. The reason is that member functions are included if and only if they are more efficient than the generic iterator based version (btw, the real inconsistency here is in requiring random access iterators for sort, but not for binary search. There's another good reason to use the member function-- the generic one can't be used on a list!)

      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.

      20% ? The class has 36 member functions, counting overloads and const/non-const pairs, so that gives you 7. operator[] (const/non-const), assignment, a default and copy constructor, a destructor, begin(), end(), size(), and empty() already put you a long way over (that's already 12 of the member functions). I don't forsee you doing anything useful without using at least 6 member functions. As for "concise functional heirarchy", there is one-- the vector,list and deque are sequence containers, and the maps and sets are associative containers. Think of these as "abstract base containers". These "abstract" container families have common requirements.

      The auto_ptr<> type has numerous logical and practical problems,

      The decision to include auto_ptr as the only smart pointer was a terrible mistake, especially since its semantics (transfer-copy) are inconsistent with the way the rest of the library works-- the library is consistent with a value semantics approach-- that is, a deep-copy policy.

      I agree that "one size fits all" doesn't work. The sensible thing to do would be to include several different smart pointer classes (like the collection offered by boost). If one must choose a single one, a deep copy pointer seems sensible.

      I'm still not convinced that automatic garbage collection is a good idea in most applications;

      Smart pointers are NOT "garbage collection". But they are a very good idea. I agree with your notion that they are not a license to be ignorant about resource management, and that thinking about them this way leads to chaos. However, they are useful in that they let you choose an appropriate ownership model for a given resource. Reference counting (shared ownership of a resource) is one such model. Deep copy/value semantics is another model.

      BTW, auto_ptr wasn't intended to be a general cure-all. Several auto_ptr proposals were submitted, and the ugly duckling auto_ptr was the only one that made it through the process.

      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.

      That's what we have. Take a look at the member functions in any of the STL classes. There are relatively few. I count 46 in std::vector.

    2. Re:Wishing Ourselves to Death by ChaoticCoyote · · Score: 2

      Good reply; I'll respond to just a couple of your points:

      In terms of refinement, I'm all in favor of avoiding changes that break existing code. Of course, the original C++ Standard broke some code when it was approved, as do almost all new standards. It's a cost-benefit choice; I prefer maximum benefit for minimal cost, without hamstringing the language's ability to grow.

      In its original form, C++ derived from C, with a goal of "as close to C, but no closer" as iterated by Stroustrup and Koenig. The C99 Standard contains design decisions incompatible with C++; thus, in the future, C++ will no longer be upwardly compatible with C. The whole episode is raft with human politics, but the end result is that what was once true is now false.

      While it might be a good idea to implement set/map/vector in certain ways, the reality is that the standard provides no guidance on implementation (which is good), leaving vendors to make bad choices. An excellent example is the performance of vector, which varies by a factor of three between various Linux compilers. The code may be portable, but the performance may not. I pick a fast part of STL under Linux, and it runs like a dog under Windows... ugh. I don't want the Standard to specify implementation (see the horrors of rand()!), but I'd also like to see strong guidelines that keep the language consistent.

      I stand on my "20%, 80% of the time" statement. Most of the time, I create vectors, push things into them, get the begin and end iterators, and destroy them. About 20% of the time, I use other methods. And on high-performance code, I dump vendors in favor of good, old-fashion C-style arrays.

      One last note: I didn't say smart pointers were equivalent to garbage collection -- however, there should have been a paragraph break there somewhere.

    3. Re:Wishing Ourselves to Death by elflord · · Score: 2
      While it might be a good idea to implement set/map/vector in certain ways, the reality is that the standard provides no guidance on implementation (which is good), leaving vendors to make bad choices. An excellent example is the performance of vector, which varies by a factor of three between various Linux compilers.

      Unfortunately, I don't see any way the standard itself can address this. I'm not clear from your post whether it's the compilers themselves or STL implementations that are at fault either. If I had to guess, I'd guess that some compilers are optimising more than others. Note that you need to turn on optimisations to avoid copping big "abstraction penalties", especially with vectors that have non-trivial iterators (ie the iterator is not a typedef or pointer)

      I agree that this notion of "portable performance" is a real and serious issue, but I think this problem is not the fault of the standard-- it's largely a problem with implementations (with the exception of std::string, which might or might not be reference counted) I'm not sure what could be done to the standard to improve this.

  172. Re:maybe because MS doesn't implement the standard by Xentax · · Score: 2

    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.
  173. Subverts Polymorphism by Martin+Spamer · · Score: 2


    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.

  174. Re:hey! lay off Java by ajs · · Score: 2

    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.

  175. OO + generic programming: The complete solution by Per+Abrahamsen · · Score: 2

    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.

  176. Re:Not all compilers support it, god-awful comp er by Daniel · · Score: 2

    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!
  177. Re:STL Downsides? by Tattva · · Score: 2
    String in itself has more functionality than most people need. Most of the STL containers do for that matter. Part of the advantage to the STL is that as templates, only the parts you actually use are compiled into the program. If your derivation is in turn a template class as well, you retain this advantage. And even if your derived class is a specific type instance, the linker will remove uneeded code. If you argument applies not to code generation, but just the amount of functionality in the class, your complaint could just as easily be leveled against the whole of STL.

    My word choices in my argument weren't perfect, what I meant to say is that you shouldn't add more functionality than everyone using the class will need. Since everyone using STL is huge, the only consideration the STL designers need to make is if enough people will use it and the operations are integral enough to the class that the added confusion the extra methods add to those who do not need them is offset. I admit that vector vs. list is contrived, but I think my argument stands regarding polymorphism vs mental models.

    I understand the convenience of the decorator design pattern over aggregation and extension, but the decorator is there for when you need to plug new functionality in situ polymorphically, which is generally not the case for a utility class like basic_string (the class operates only on memory data and copying and conversion are reasonable alternatives.) Your examples seem to indicate your class doesn't need to have a is-a relationship to basic_string, it only needs the functionality of basic_string, so is-a becomes a source of confusion (and possibly defects if users of your class take advantage of that relationship by casting and therefore possibly failing to call your non-virtual destructor) to other users and only saves you a couple of hours of pounding on the keyboard to write wrapper methods for your new class that delegate to a contained basic_string instance.

    --
    personal attacks hurt, especially when deserved
  178. Re:C++ is a horrible language. by elflord · · Score: 2
    So, building all library variants - static/shared/repo/optimized becomes a major PITA.

    The answer to this one is simple-- never trust a vendor who forces you to instantiate templates a certain way. Especially one that forces you to use -frepo (oh, and never use -frepo ... )

  179. Not a fair comparison by Tharsis · · Score: 2

    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.

  180. Generic Algorithms are the Downside by gstover · · Score: 2, Informative

    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

  181. Re:Butchery of "Effective STL" by Myers by lkaos · · Score: 2

    Yeah, I corrected myself a little further down :) Stupid HTML...

    Preview, what's that for :)

    --
    int func(int a);
    func((b += 3, b));
  182. Re:STL Downsides? by lkaos · · Score: 2

    I looked at the hawkstein/lkaos debate

    That's a cleaver way of referring to a /. discussion :)

    I haven't read Modern C++ Design, and I will probably take you up on your advice, but I would at least like to point out that the "debate" ended in the realization that his example could be implemented easier and more efficently *without* using inherentence (sp.).

    I still stand by my point that there is no good reason to inherent from an STL container (although there is one justifiable reason that I had to conceed to in another thread...).

    That is because C++ does not support template typedefs so using inherentence to simulate template typedef'ing is excusable.

    I actually agree with your explanation of generic programming and I'm curious to see what you thought my view on it was as our conservation regardded inherentence, not generic programming (unless we had another thread going to somewhere).

    --
    int func(int a);
    func((b += 3, b));
  183. Re:Not all compilers support it, god-awful comp er by ahde · · Score: 2

    cough*kyoto*cough!

  184. Re:About maps... by J.Random+Hacker · · Score: 3, Insightful

    I know this thread should really be dead, but I have to respond. I'm not confused at all. I know in great detail what I'm talking about. Here's the scoop:

    Hash tables have *amortized* constant time lookup, but worst case behaviour is linear. There are two basic approaches to hash table construction, and they degrade in slightly different ways.

    Open coded hash tables use (something like) a vector of cells indexed by the hash value. If there is a collision, you rehash (compute a new and different hash) or scan for an open cell and use that. In either case, you keep going till you find something. This leads to linear scan on a nearly full table. Maintaining these requires the rehashing process you describe.

    Bucket hash tables used a list in each cell. You hash to the cell, then scan the list. In this case, an over-full hash-table has long lists to scan. Again, linear in the worst case.

    In both cases, we're assuming a good hash function. One easy way to get poor performance out of a hash table is to have a poorly performing hash function.

    Now, with respect to the STL, the issue for the designers was, in fact, worst case performance; not expected case performance. Call it a design guideline if you will, but that is what they used as a criterion.

    So, as I said in my earlier post, Hash tables were not in the standard because they have poor *WORST CASE* performance. Never-the-less, the good folks at SGI have produced several high-quality hash table implementations that are STL compatable (so have I, for that matter). At some future time, I expect that those hash tables will be added to the STL because they are quite useful, when used properly.

    There are several good works on the topic. Knuth's "Art..." being the seminal work on complexity. He covers both types of hash tables in detail in volume 3. I also recall a paper by Stepanov discussing both the ideas behind the STL and the tradeoffs. It's fairly old -- circa 1990 or so IIRC.