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

946 comments

  1. Lots of overhead. by billnapier · · Score: 0, Informative

    This may really only be a major concern for embedded and realtime platforms, but there is a lot of overhead with using the STL. Virtual functions and things of that like can make your code bigger and slower. The impact may not be noticed on a desktop system, but can cause havoc on your real-time requirements if you're not aware of them.

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

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

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

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

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

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

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

    9. Re:Lots of overhead. by Anonymous Coward · · Score: 1, Informative


      There are no virtual functions in the STL. From an embedded developers stanpoint, the biggest drawback to the STL would probably be binary code size.

    10. Re:Lots of overhead. by yumyum · · Score: 1

      For I/O, perhaps. But all of the STL containers I've seen are templates with no virtual functions. Vendors may do things differently, but I've used GNU, Sun's Forte (RogueWave), and STLport and a grep of all of the them show just I/O and related virtuals.

      Since most of the STL type checking evaporates during compile time and potentially inlines, your code just might be faster and with less overhead than otherwise. I'm addicted to the std::for_each function myself.

      Brad

    11. Re:Lots of overhead. by Anonymous Coward · · Score: 0

      Anything you do will cause havok if you aren't aware of it, but that doesn't generally include virtual functions since it's easily timed if you need to. You didn't make a comment about templates, and it doesn't bloat your code when any more than having to rewrite the functions when you're dealing with the equivalent of different template instantiations. So, I'm afraid you're still full of it.

    12. Re:Lots of overhead. by 56ker · · Score: 0

      What does STL stand for?

    13. 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.
    14. 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
    15. Re:Lots of overhead. by Anonymous Coward · · Score: 1, Funny

      What does STL stand for?

      Show The Love! It was result of a fierce debate between the STL architects.

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

    17. Re:Lots of overhead. by lazarius · · Score: 1

      What does STL stand for?

      Standard Template Library.

      MIKE

      --
      Beware the JabberOrk.
    18. Re:Lots of overhead. by MobyDisk · · Score: 2

      Standard Template Library

    19. Re:Lots of overhead. by Anonymous Coward · · Score: 0

      Apparently you only write braindead applications that don't ever need data-structures. Have fun with that front-end...

    20. 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.
    21. 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;
      };

    22. Re:Lots of overhead. by nonya · · Score: 1

      Arg! The above code lost the "less than" and "greater than" chars when coverting to html. Of course, the above code should read: template "less than char" class TIter "greater than char".

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

    24. Re:Lots of overhead. by thomas.galvin · · Score: 1

      If you want a container of intgers in a Java container (i think) you have to have a container of "Int" rather than "int".

      Integer, actually, but otherwise you are correct. They are implmenting an auto-wrap feature in Java 1.5, but even then, primitives will still be wrapped with objects; it will just happen behinde the scenes.

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

    26. Re:Lots of overhead. by billnapier · · Score: 1
      For example, a container of int * and a container of char * might use the same object code.

      But that argument only holds true for the basic types (of which there are only a handful). If you start using containers of classes, you can't make that optimization.

    27. Re:Lots of overhead. by billnapier · · Score: 0
      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.

      If you'll kindly read the original post, I was talking about memory constrained environments. If you're running on a full fledged PC, we are picking nits. Today's PC's have more RAM then they know what to do with (hence WinXP).

      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?

      15 separate classes is the same things as template classes, except with typing involved. You'll end up with pretty much the same amount of generate object code (with the possible exception that you can (possibly) reuse some of the template generated code with the basic types like char and int).

      We're faced with a classic engineering problem here. It's a tradeoff. We can use templates and go for bloated code, or you could use inheritance/virutal functions and go for the runtime speed. Classic memory/speed tradeoff

    28. Re:Lots of overhead. by Anonymous Coward · · Score: 0

      You're really talking out of your ass, do you know that?

      First of all, inline functions tend to be the smaller and more efficient way of generating assembly code than procedure-calls.

      Second of all, using templates means that code you never use will never actually be generated and linked into your final binary.

      Third, the burden is on the compiler. "Everyone" (75% of all STL programmers ;) knows a big C++ w/STL project with lots of custom templates can really kill compile-times. However, using precompiled headers can alleviate this somewhat.

      Fourth, the worst critisism against STL is probably the cryptic code that eventually makes it impossible to understand what's going on. This is however the fault of the programmer. People shouldn't really let the code be the documentation.

      Fifth, the template errormessages in most compilers could really need a fix.

      You just don't have a case, do you? Read some more, I'm sure there are more valid critisism on STL, but your arguments are really really OLD. Come back with something groundbreaking and destructive in say, 20 years.

      Myself, I go the positive route, and I'm not stuck in the old C-age.

    29. Re:Lots of overhead. by PuntaConejo · · Score: 1

      You are right that containers of two different class types cannot use the same object code.
      But in my example, I refer to containers of pointers. As Stroustrup discusses in section 13.5 (3ed.), a container of int * and of Shape * _can_ share the same object code.

    30. 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.
    31. Re:Lots of overhead. by Anonymous Coward · · Score: 0

      No, you don't understand. Templates don't have overhead at all - theoretically not a single bit -over manually constructed 15 classes. So STL here is clearly a winner.

      An arguable downside is the requirement to relearn to do things differently.

    32. Re:Lots of overhead. by Anonymous Coward · · Score: 0

      Standard Template Library

    33. Re:Lots of overhead. by cpeterso · · Score: 1

      Standard Template Library.

    34. Re:Lots of overhead. by macrom · · Score: 1

      This is a myth that I wish would just die...

      I've worked on plenty of commercial apps that use STL, all without problems. You are just like the die-hard ANSI C people that still think C++ is inherently slower than C. It's not the STL itself that is (always) the speed reducer, but the programmer that doesn't understand the proper tools to use to avoid slowing code down.

    35. Re:Lots of overhead. by Anonymous Coward · · Score: 0

      standard template library

    36. Re:Lots of overhead. by Anonymous Coward · · Score: 0

      Standard Template Library.

    37. Re:Lots of overhead. by Anonymous Coward · · Score: 0

      wow someone wrote libs for other to use. whowudathunkit.

    38. Re:Lots of overhead. by user2048 · · Score: 1

      True, the C++ language spec explicitly specifies performance requirements for STL components. But only in terms of how the performance scales for large sets of data - the Big-0 performance. This doesn't require that any of it is actually fast on any absolute scale. (I think.)

    39. Re:Lots of overhead. by drxenos · · Score: 1

      Oh horse pucky. I've been using stl in real-time, embedded systems for a few years. Code-bloat and performance are not an issue. And anyone talking of "virtual functions" knows nothing of stl. Besides, if it did use them and your system can't handle the extra nanosecond to do a virtual function call, you have bigger problems. As for code bloat, if you have that problem, you don't know how to make proper use of the library.

      --


      Anonymous Cowards suck.
  2. No by Anonymous Coward · · Score: 0

    Use your own functions. Remember linus, real men code all from the ground up.

    1. Re:No by Anonymous Coward · · Score: 1, Funny

      ground up? right. im sure you're using a computer you whittled together from resistors and capacitors - each of which im sure you created out of the natural elements. you dont want to leverage anybody elses work you know.

    2. Re:No by iow · · Score: 0

      it is!

    3. Re:No by Anonymous Coward · · Score: 0

      Anything with either of the words "Basic" and "Scripting" or "Script" cannot be considered programming. Lots of things that use the suffix "Cad" also do not count as programming. Some people.

    4. Re:No by jerry924 · · Score: 1

      I can write scripts with c++, therefore it must not be a language either huh?

    5. Re:No by trang-oul · · Score: 1

      it is obvious he is referring to interpreted languages. :)

    6. Re:No by mini+me · · Score: 1

      But there is a C/C++ interpreter.

    7. Re:No by Anonymous Coward · · Score: 0

      I know I am feeding a troll, but I don't know why you included "things that use the suffix 'cad'", since AutoCAD's lisp is very powerful stuff indeed.

      I can at least understand your attack on Visual Basic, VBScript and Javascript, although of course they are real and fully-fledged programming languages.

      graspee

  3. 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 Anonymous Coward · · Score: 0

      Parent is not troll...
      Parent is funny...
      please read post before modding!!!

    2. Re:One Downside by Anonymous Coward · · Score: 0

      +3 Funny? That's a real downside.

      (I have been teaching C++ to 1-2 year students, I still think Java is so much better.)

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

    4. Re:One Downside by Anonymous Coward · · Score: 1, Interesting

      Yes, thank you for pointing this out.

      I think it needs to be said: As a high-level language, C and it's derivatives barely fit the definition. C has always been called "high-level assembly", and it's absolutely true. C is -great- for low-level work...but why in God's name are we pretending it is a competant high-level language? It is NOT on the same level as the languages you mention. In fact, it is not even on the same level as Pascal.

      The nice thing about Python, Ruby, et al is that you DON'T need to know the full ins and outs of the language to be able to use them effectively.

      And of course, there are the security issues of C (that aren't present in other languages)...

    5. Re:One Downside by Anonymous Coward · · Score: 0

      Well said. I totally agree.

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

    7. Re:One Downside by YOND+R+BOY · · Score: 0, Interesting

      C++ depresses me. I feel like the whole world is jumping on some buzzword bandwagon. Personally I dont understand... C++ makes it easier to produce bloatware (which is apparently rewarded in the M$ world) and it has the added disadvantage of objects. Hey, at least its not Java which forces OOP on you instead of giving you an option. I can't really talk about the STL (partly because I have never used it and partly because it would depress me) but from the coders I do know who have used it, it is a sad sad mechanism for making your code slower and harder to debug and your executables larger

    8. Re:One Downside by Anonymous Coward · · Score: 0

      Stroustrup once said something like, "Compared to C, C++ makes it harder to shoot yourself in the foot, but when you do, you blow your whole leg off".

      Your point about having to know all that shit is good as well, especially as an argument to the old pro-C++ saw about not having to use what you don't want. It's just not true, you need to know about all this crap to make any use of the language. Every C++ programmer I know sits at his desk with a language ref at his side.

      Also, on the topic of Java's OM vs. libs, it's another example of how they should have split up the language, libs, and security model (as JWZ has spoken on in the gruntles)

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

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

    11. Re:One Downside by Anonymous Coward · · Score: 0

      Personally I dont understand

      Right, you have no idea what you are talking about. Your statements are completely off base.

      Learn, then speak.

    12. Re:One Downside by Anonymous Coward · · Score: 0

      Your definition of good certainly sounds different but I wouldn't call it reasonable.

    13. Re:One Downside by Talonius · · Score: 1, Offtopic

      And hey, at least it's not C#. : )

      -shrug- I've been looking at using C# in the ASP.NET model as a backend for our application here (porting over to a thin client) and have been amazed at the level of effort that Microsoft put into making ASP.NET backwards compatible.

      While ASP.NET does work better and faster when running under Internet Explorer than under Netscape Navigator the web pages when viewed using Netscape remain completely capable; there is no loss of functionality due to browser change.

      As for C# itself it's a language that's meant to keep the system clean. By automating things such as garbage collection, ensuring that variables must be initialized before use, and making the passing of reference and value types more distinct, it does what it sets out to do - ensures that the programmer can concentrate on -high level- stuff rather than low level - and not worry about whether or not he's causing a buffer overrun because he's working at 2AM and 3 weeks behind a deadline.

      C# is -not- Win32 specific. I can't wait for Miguel to get his port of the CLR done so I can start using it as a language under the Linux platform. I personally view C# as a -great- programming language. I viewed it with distaste when I began but now very much think of it in a positive manner.

      As for why Microsoft - we run MS SQL 7 on the backend; we're not going to switch to Oracle just so our database server can move to a *nix variant, ASP.NET integrates (quite, quite nicely) with MS SQL. This move does alleviate our requirement to run Win32 desktops which was a goal of mine (whether or not our networking department makes that shift is up to -them- but I don't want to be blamed for locking us into a Microsoft shop) - only our backend needs to remain Microsoft.

      Mod as a troll or flamebait as you like. This is just my opinion. :)

      --
      My reality check bounced.
    14. 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
    15. Re:One Downside by Anonymous Coward · · Score: 0

      I've always wondered... why it seems everything higher level is interpreted, not compiled. Are there any good high level application development languages that compile to machine code?

    16. Re:One Downside by Anonymous Coward · · Score: 0

      Yes lots

      My favorite is the Visial Prolog compiler, a nice dome since the language was never designed to be compiled

      http://www.pdc.dk

      And Pascal/modula derivaties with memory managent such as Oberon (A VERY classy language) and Modula3 (althogh some oberon systems partly compile and have a small intepreter stub most are true compilers, XDS for instance)

      but there are many others incuding such old favorites as Basic :)

      There are even 5GL database compilers that turn out amazingly fast code

    17. Re:One Downside by Anonymous Coward · · Score: 0

      Come on - his definition of reasonable was within reasonable set of definitions of reasonable.

    18. 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.
    19. Re:One Downside by Anonymous Coward · · Score: 0

      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.

      Good point. For example, some people make the mistake that just because java can be compiled down to native that it will be as fast as straight c. What some people don't realize is that to support the "higher-level" facilties of a language like java, the compiler has to generate many more instructions

      You could make the argument that something like "hot-spot" technology should make java bytecode faster than java compiled code. I'm sure sun does:)

    20. Re:One Downside by melee70 · · Score: 1

      so basically all of you that are complaining about C++ seemed to be saying the same thing. You actually have to learn something for once. If you don't know what you are doing you can really screw things up. That is so horrible. Maybe that's why they have tests in school and maybe that's why you should have actually learned the material. Half assed wanna be programmers that don't know what the hell they are doing will always screw things up and then complain about it.

      The power and complexity of C++ just makes it much easier for these wanna be's to mess things up.

    21. 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
    22. Re:One Downside by Anonymous Coward · · Score: 0

      Bloody limey. Go home.

    23. Re:One Downside by Matthew+Austern · · Score: 1
      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.

      Assuming you want to use newfangled languages like C in the first place, of course. What's wrong with FORTRAN IV and LISP 1.5?

    24. Re:One Downside by Anonymous Coward · · Score: 0

      Hmmm... I suppose that's reasonable...

    25. Re:One Downside by Anonymous Coward · · Score: 0

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

      hhahah you stupid shits make me laugh
      "uh dat der language is too powerfull, makes your head hurt to use it, you should code in object oriented basic"

      SORRY THAT YOU ARENT GOOD ENOUGH TO EMBRACE C++

    26. Re:One Downside by jonelf · · Score: 1

      > ASP.NET integrates (quite, quite nicely) with MS SQL

      But it also integrates it in a way that makes switching to another DB alot harder than with with old ADO/OleDB. If you use System.Data.SqlClient that is. And you do because it is much faster than System.Data.OleDb for alot of simple things like connectiontime. MS should off course have hidden the type of DB from the programmer. Why didn't they do it? Why do they have SqlDataReader and OleDbDataReader and not just a DataReader interface that inherits from Sql or OleDb? My paranoia tells me that MS wants to sell SQL-server licenses instead of helping selling Oracle or DB2.

      --
      /J - to know recursion you must first know recursion
    27. 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?
    28. Re:One Downside by JonK · · Score: 1
      not just a DataReader interface that inherits from Sql or OleDb


      They do: it's called IDataReader. Go away, read about interface-based programming and then come back and rewrite your comment above (hint: you declare an instance of the interface, bind it to a concrete class such as SQLDataReader or OleDbDataReader and then make all your calls through the interface)


      Jeez, some people

      --
      Cheers

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

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

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

    33. Re:One Downside by Misfire · · Score: 1

      What data has the array been populated with? If it's an auto array, I presume that it contains random stack contents. That being the case, how can you say anything about the relative performance of the C and C++ versions, if you can't guarantee that each program even sorts the same data?

    34. Re:One Downside by Anonymous Coward · · Score: 0

      kinda sad that after over 10 years you still can't learn a language..

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

    36. Re:One Downside by lubricated · · Score: 1

      stop smoking crack, that is not how you do it. unless you love to waste unneded stack space.
      how about
      my less than sign probably wont make it but,
      return *((int*)x) *((int*)y)
      or even eisier declare compare as
      int compare (int* x,int* y)

      --
      It has been statistically shown that helmets increase the risk of head injury.
    37. 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.

    38. Re:One Downside by matteo_v · · Score: 1

      Ahem, just for the sake of being pedantic...

      the proper way to code the compare function is something like

      int compare(const void *a, const void *b) {
      int x = * (int*) a;
      int y = * (int*) b;
      if (x < y) return -1;
      if (x > y) return 1;
      return 0;
      }

      Your compare functions were all flawed; the resulting array was likely
      not sorted at all.

      Also, some people complained that casts to int* from void* are
      inefficient. This is certainly not true! The binary representation
      of a pointer to "void" does not change when the pointer is cast to
      int. The casts are just a way to manipulate the C type-check system;
      in the case of casts from a pointer type to another no change of
      representation is needed.

      Finally, the reason why the templated C++ sort _should_ run faster
      than the C version is that in C you have the overhead of a function
      call for each comparison. The beauty of the template mechanism is
      that if "<" is really the native less-than-between-ints, rather
      than an overloaded operator, then it will be inlined.

      --
      -- http://matteo.vaccari.name/
    39. 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.
    40. Re:One Downside by Anonymous Coward · · Score: 0

      High Level languages ? You call the pathetic chicken scratching that Smalltalk is, a HIGH LEVEL LANGUAGE ? GMAFB. And PERL ? Perl has about the structure and order that a 4 year old can put together with a deck of cards.

      Yeah...you could write an accounting package in Smalltalk...but the question is....why did the psychiatrist let you out of the ward to actually LET YOU do so ?

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

    42. 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. :-/
    43. 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.
    44. 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.
    45. Re:One Downside by Anonymous Coward · · Score: 0

      Your "new" code fails when *first or *second is zero.

    46. Re:One Downside by iGN97 · · Score: 1

      STL's sort is almost always faster than quicksort. This is because the sort can be implemented without doing a function call (even with user-defined compare-functions).

      From "Efficient STL" (Scott Meyers), sort is measured to be upto 670% faster than C quicksort. This is from a couple of real-life tests Meyers did, and is by no means an absolute number on STL's sort speed.

      The STL is sweet, it produces efficient code, than the source speak for itself; tasks like this are very hard to screw up.

      eeGN

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

    48. Re:One Downside by jonelf · · Score: 1

      Your right and I'm wrong. Now I will dig a very deep hole and live there until everyone forgot about my previous post.

      Here is a nice example of doing what you just proposed:
      http://www.codeproject.com/csharp/dal.a sp

      I still believe that MS should have provided us with a generic DB-layer that the programmer configured to use SqlData, OleDBData or whatever. Now every example is SqlClient or OleDbClient and thus makes idiots like me doing things the wrong way.

      Thanks for enlightening me!

      --
      /J - to know recursion you must first know recursion
    49. 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!
    50. Re:One Downside by Anonymous Coward · · Score: 0

      I think Java and Perl are different tools for
      different purposes.

      there is a superset of C interpreter (Ch from
      www.softintegration.com) for scripting. I think
      it sits between C and C++ for high level language.
      I like it since it has some good features of
      other scripting language while not having
      the complexity of C++ with template stuff.

      I would say language design has lots of compromise on different issues.

    51. Re:One Downside by Anonymous Coward · · Score: 0

      I always find it amusing how c++ programmers go to great lengths to prove that their chosen langauge is the be all and nd all of languages. Yes c++ is exellent for some things, but there is no denying that overuse of c++ results in slow / bloated code.
      I program in c and C++ every day at work and unlike most c++ or even c programmers the truth of the matter is use c++ if it has things you really need otherwise c will produce small faster and usually better code. Of course if you are a crap proggrammer you will produce crap code no matter what language you use.

    52. 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.
    53. Re:One Downside by gmarceau · · Score: 1
      want functional programming? C++ has the tools (awkwardly, but they're there).

      Well, you probably know this, but I'll add it for the record. Quickly put, fn-prog is about having all your variable constant, subtituting copy+recursion for assignments.

      Lack of both lambda's and tail recursion prevents a blanket usage of fn in C++. In non trivial cases, you will find those feature necessary to compose the right copy+recusion combo.

      Unfortunatly, even is fairly simple cases, C++'s lack of const parametrisation will prevent a smooth fn-style. For example :

      const Window &select(const Window &a, const Window b);// returns either a or b depending on something else

      Passing two non-const Window to such a select() will unnecessarly return a const Window

      What you realy want is :

      template&lt specifier CONST_OR_NOT>CONST_OR_NOT Window &select(CONST_OR_NOT Window &a, CONST_OR_NOT Window b);

      But that isn't C++. C++ will force you to duplicate select()'s code or to cast in and out of constness. When coding for maximal constness, you regularly runs into this choice between two unsastifactory options, which eventualy motivates most C++ programmers to stop using const altogether.

      --
      This post was compiled with `% gec -O`. email me if you need the sources
  4. 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.

    --

    -

    1. Re:buggy implementations. by zaphod110676 · · Score: 1

      This is true but the beauty of C++ is that you can implement the obscure, ugly stuff once and burry it in a class with whatever type of interface you would like to use. Abstraction is your friend.

      --
      To Do: 1. Take over world 2. Pick up Milk and Bread on the way home
    2. Re:buggy implementations. by lib · · Score: 1

      Bugs are one of the few drawbacks ive seen with the STL. Even where they exist, its not that hard to avoid them due to the number of member functions which overlap...

      the linked list class is an example of this (bare with me, Someone i worked with found this problem and its been a few months since ive looked at it)..
      Depending on how you use erase, if you keep calling the function untill the entire list is empty, invalid pointers seem to exist within the container. IF you then add a few elements (i believe it was two push backs in this specific case) the entire list gets hosed.
      Ive only tried/seen this on the SUN implementation.

      Though this is annoying, its easy to avoid this with all of the member functions you're given to play with... Just knowing its there becomes sorta screwy.

    3. Re:buggy implementations. by cookd · · Score: 1

      Most of it could have been ok, but the explosion that occurs with template expansion forced really tiny variable names. Most STL implementation code could be at least somewhat readable if it only had some real variable names and a few comments. As it is, I stare at it until inspiration comes (or I run out of Caffeine and fall asleep, whichever comes first).

      --
      Time flies like an arrow. Fruit flies like a banana.
    4. Re:buggy implementations. by Anonymous Coward · · Score: 0

      Yeah, STL can get ugly if you're clumsy with it. But have you looked at Rogue Wave code? Bleurgh! Those guys use 1,000 templates to do what the STL does with a dozen. STL every time!

      BTW, the best STL book I've seen is "The C++ Standard Library" by Nicolai M. Josuttis.

  5. 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."
  6. What virtual functions? by Anonymous Coward · · Score: 1, Informative

    The STL uses templates, not an object hierarchy. And code that's heavily optimized for speed. Everything I've read has said that performance isn't an issue.

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

    2. Re:What virtual functions? by Anonymous Coward · · Score: 1, Insightful

      It only generates code for what you instantiate. What code do you expect to write to support those 15 different types of things in C when you hand-write it and all the algorithms for it?

    3. Re:What virtual functions? by soft_guy · · Score: 1

      The post I'm replying to could be confusing to some C++ or STL newbies. If I use *a* vector to hold fifteen different objects *of the same type*, the compiler generates one vector class (and one instance of that class). 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.

      --
      Avoid Missing Ball for High Score
    4. 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));
    5. 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.

    6. Re:What virtual functions? by SLOGEN · · Score: 1
      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.
      1. That's probably also required, since different code should execute when the template parameter changes, for instance the copy-constructors, assignments, comparison and such are different.

        One candidate for code-sharing is "int size_t e() const", but many such candidates are so small inlining is shorter than funcall.

      2. C++ has no requirement for seperated code-generation. It would be perfectly legal to compile template clas-code into shared functions for different parameters, where it is possible. That no compilers do it is an unfortunate fact :(

      Example:

      struct Timer {
      inline void begin(const void*) { ...; }
      inline void end(const void*) { ...; }
      }
      struct Foo {
      virtual void bar(Timer& timer) const = 0;
      }
      template <typename T>
      struct Bar {
      virtual void bar(Timer& timer) const {
      timer.begin(this);
      T::bar();
      timer.end(this);
      }
      }

      Here, it would be perfectly legal for all "Bar::bar(Timer& timer) const" to share the generated code, but such cases (with substantial code) are few.

      --
      SLOGEN [ http://ungdomshus.nu : Sebastian cover music]
    7. Re:What virtual functions? by billnapier · · Score: 1

      it does not increase code size in any noticable manner.


      But it still does increase it, even if its not "noticable"

    8. 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.
    9. 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.
    10. Re:What virtual functions? by Anonymous Coward · · Score: 0

      Not so. Using map and set can siginificantly increase your code size. I work on executable image compression all day and I've had to remove a large amount of stl and replace it with home-brew version to keep the code size down. Using MSVC++, the code and debug data are kept in seperate files (the way it should be). Using a fairly simple map can add 20k to your image easily.

    11. Re:What virtual functions? by Anonymous Coward · · Score: 0

      Nonsense. I found in VC6 that each different STL container type I used, used approx 8kB. That is if I have a list and a list, then that would add about 16kB to the final (optimized) code. I'm talking about types here of course, not variables; each one of those types can be used multiple times without any extra overhead.

    12. Re:What virtual functions? by Anonymous Coward · · Score: 0

      Having written a number of small programs using map and the like, map did not add 20K to the executable. Nowhere near it. There are so many issues here. map pulls in the standard C lib so if you don't normally link with the CRT then map will add probably 35K+ using MSVC. It sounds from your description that you are replacing parts of the CRT. And some debug information is contained in the debug executable. A quick file size check will show it is bigger.

  7. ahem... by Anonymous Coward · · Score: 0

    First post? I dunno. Anyway, one of the bad things about the standard library is spotty compiler support, especially around the edges where you can have goofy things like template template arguments and so on. Still, when it works, and it works most of the time, it can be a real treat to program it. I'm becoming a big fan of it myself. Meyer's "Effective STL" is a great book about the gotchas that lurk inside the STL (there be dragons :) ). I would have loved to have gone to a session by Meyers...

  8. pros and cons of STL by Anonymous Coward · · Score: 0, Troll
    advantages:

    • unified scoping and dereferencing between classes
    • metacircular allocation, instead of the old malloc-free style
    • deferred addressing (this is more of a compilation feature than programming boon)


    disadvantages:

    • still no multiple inheritance
    • problems with template incompatibility between STL/non-STL applications
    • gay syntax
    • underpowered for serious e-commerce and business-to-business deployment.
    1. Re:pros and cons of STL by Anonymous Coward · · Score: 0

      gay syntax

      So your saying STL is the Big Gay Al of syntax? Or perhaps it's pronounced with a lisp?

    2. Re:pros and cons of STL by Anonymous Coward · · Score: 0

      underpowered for serious e-commerce and business-to-business deployment?

      What the fuck (or fsck, if you're a wienie) does the STL have to do with those silly buzzwords? Go use a library outside the standard language for that stuff...

    3. Re:pros and cons of STL by Anonymous Coward · · Score: 0

      "Gay syntax"? An interesting concept. Actually, though, I think the syntax is spic or wop or nigger or chink or cunt or kike.

    4. 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)
    5. Re:pros and cons of STL by jason_watkins · · Score: 1

      He's most likely refering to J2EE Beans or other componant systems.

      This is clear an apples to oranges issue. STL provides standard facilities, you can use it alongside with whatever componant technology you please.

    6. Re:pros and cons of STL by Anonymous Coward · · Score: 0

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

      Me too Fry, me too.. What are they though?

    7. Re:pros and cons of STL by Isle · · Score: 1

      It's a hint. Although you should have figured it out when reading the the list of pros.

      He's Karma Whoring Troll, but a good one ;-)

  9. 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 Anonymous Coward · · Score: 0
      The STL is almost entirely template-based.

      Gosh darn, who would of thought the Standard Template Library would be template based?

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

      It's true that this depends a lot on the compiler and the library. A good compiler and library will use template features to create exactly one copy of list and use it for all types of lists-of-pointers.

      Part of the reason APIs are completely illegible is, IMHO, due to all of the hack-arounds for nonstandard compilers and platforms that need to be in the headers. You normally only see this stuff inside the source code of libraries, not the headers, but in the case of STL the headers are the source code.

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

    4. Re:STL downsides by Hawke · · Score: 1
      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*

    5. Re:STL downsides by joshwalker · · Score: 1
      Thought I already said that.... *shrug*

      You sounded like you weren't sure. I just wanted to emphasize that it was nailed down, and that it's a bad idea (tm)

    6. Re:STL downsides by jungd · · Score: 1

      If you're seeing this type of bloat, it's more likely to be either a compiler problem or a really bad implementation of the STL.

      Typically a container like list is just an inlined and statically checked 'wrapper' for a more basic list that specializes on void*, or something like that. That way there should only be one set of code emitted for all lists of pointers used.

      --
      /..sig file not found - permission denied.
    7. Re:STL downsides by Hawke · · Score: 1
      If you're seeing this type of bloat, it's more likely to be either a compilier problem or a really bad implimentation of the STL.

      No real argument there. Its a non-optimized implimentation of the STL that doesn't appear to use specializations... But it not one I can easily get away from.

      [dougk@pitr src]$ ls -l privman.cc privman.o ; gcc -v
      -rw-r--r-- 1 dougk dougk14613 Apr 29 12:56 privman.cc
      -rw-rw-r-- 1 dougkdougk 290144 Apr 29 12:54 privman.o
      Reading specs from /usr/lib/gcc-lib/i386-redhat-linux/2.96/specs
      gcc version 2.96 20000731 (Red Hat Linux 7.1 2.96-98)

    8. Re:STL downsides by Todd+Knarr · · Score: 1

      I meant the implementation is heavy on templates internally too. As in you can get templates nested 3 and 4 and more levels deep on even apparently simple code. The worst I saw working with it was a type signature for a 3-argument function that took 7 100-character lines to print out with all the types expanded all the way and enough angle-brackets to match up to make even a hardened Lisp programmer nauseous.

    9. 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
    10. Re:STL downsides by Heinrich · · Score: 1
      You'll probally want to get a book or other such better documentation.

      If you want to do serious work with the STL, it might be a good idea to take the original ISO 14882-1998 standard for C++ which is available for US$ 18. Many of the fine points are unfortunately missing or simply plain wrong in the manual pages of various C++ STL vendors and/or in various STL books.

    11. 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.
    12. Re:STL downsides by Anonymous Coward · · Score: 0

      yep, another open source success story.

    13. Re:STL downsides by SlaterSan · · Score: 1

      You can write your own allocators for lists which allow you to decide how you want to work with memory.

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

    15. Re:STL downsides by Anonymous Coward · · Score: 0

      Depending on your compilier, you might end up with excessive binary-code bloat, as three different copies of "list" are created for list , list, and list instead of using a single specilization for all three.


      The best way around this is to template the interface and have a generic implementation based on void *'s.
    16. 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.

    17. Re:STL downsides by Snoopy77 · · Score: 1

      I have found SGI's documentation to be pretty good, bordering on great actually. And if ever it was not enough I just do the usual thing and hit the newsgroups for an example.

      Personally, I would recommend making the STL your friend. Once you get to know him he'll be a great help.

      --
      "She's a West Texas girl, just like me" - G.W Bush Iraqis
    18. Re:STL downsides by st.kitts · · Score: 1

      Solved easily by specialization. You should do something like:

      template <class T>
      list { /*...*/};

      template <>
      list <void*> { /* specialize for void* */ };

      template <class T>
      list<T*> : private list<void*> {
      typedef list<void*> Base;
      /* Forward all operations to Base */
      };

      Infact, Stroustrup talks extensively about this technique which he himself has applied a lot. In fact this technique can be applied to all classes which need to hold pointers. One more way to avoid code bloat is to place all operations that don't depend on templated type in a common base class and then derive your template class from this. This way you won't have multiple copies of functions, data members etc which don't depend on the template type.

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

    20. Re:STL downsides by Anonymous Coward · · Score: 0

      Here's a nickel, kid - go buy yourself a computer and actually try writing some code.

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

  10. 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 Anonymous Coward · · Score: 0

      Not include in the .NET SDK, but included with the full VC++/VisualStudio products

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

      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)

    3. 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
    4. Re:Not supported in C++.Net (??) by macrom · · Score: 1

      MS using a subset of C++ has nothing to do with the language-independent nature of the CLR. It still maintains that feature, it's just the .NET version of C++ that gets watered down.

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

    6. Re:Not supported in C++.Net (??) by Zoarre · · Score: 1

      > so much for M$'s claim of language independence
      > for the CLR... hehehehe

      It was a faulty claim from the start...

      I can't see how .NET can claim language-independence if it mandates an OO programming model. All of things about alternate languages that interest me happen to be those things that break the .NET language paradigm!

      --
      "People with opinions just go around bothering one another." -The Buddha
    7. Re:Not supported in C++.Net (??) by Anonymous Coward · · Score: 0

      The CLR is language-independent. This means that you can (in theory) use C#, VB.NET, C++, Perl, COBOL, Python, bla bla, to access the functionality within the CLR. Whether or not the .NET version of C++ supports all of the features of ISO C++ is irrelevant. You can still access the CLR from many different languages.

      Stop confusing language independence with a platform's implementation of language features.

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

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

  12. Re:Downsides to Deep Anal by Anonymous Coward · · Score: 0

    I encourage you to encourage her to get a strap-on dildo. It's absolutely fabulous to get fucked in the ass by your girlfriend. Just take your time to get used to the dildo up your ass.

  13. A list of digital theatres: by quakeroatz · · Score: 0

    Digital Theatres

    And there are a few in Canada, most notably:
    Famous Players Paramount
    259 Richmond St. West
    Toronto, Ontario Canada M5V3M6
    Tel: 416-368-5600

    Go raps!

  14. 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 Wolfier · · Score: 1

      (OT) I'm doing almost identical stuffs as you do - I bet you have found that good ACE documentations is even harder to come by than good STL documentations....

    5. 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.
    6. Re:Not many by SLOGEN · · Score: 1

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

      This is hope-fully implicitly understood by users of data-structures, at least if they are able to code C++ :)

      What you should remember, is to utilize the C++ methods for type-alias: typedef, to make it much easier to swap data-structure implementation, and or even parametrize by the data-structure as a template param (often with a default).

      --
      SLOGEN [ http://ungdomshus.nu : Sebastian cover music]
    7. Re:Not many by joshwalker · · Score: 1
      String isn't threadsafe in Solaris either; I believe that's actually SGI's implementation.

      Depends on what compiler you're using. AFAICT, string from Forte 6 is threadsafe (COW* with atomic increment). gcc 3.0's string is also threadsafe (COW with atomic increment). Other platforms may be threadsafe by simply not implementing COW (STLPort, for example). string on MSVC 6 is definitely _not_ threadsafe (COW, but no atomic inc); I think gcc 2.95 is the same.

      *COW = Copy On Write

    8. 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.
    9. 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.
    10. Re:Not many by Anonymous Coward · · Score: 0

      I agree. This is a feature, not a bug. You should know how the underlying datastructure is supposed to work from the name and what the implications of that are. That's why they have different ones and they are not called "collection" or something.

    11. Re:Not many by gkatsi · · Score: 1

      The community right now seems to think that COW is ok for single-threaded uses, but the locking overhead is too high in multithreaded uses and you may prefer to avoid it in those situations. Actually performing an allocation+copy turns out to be faster than locking and unlocking the shared representation.

      Of course, using the atomic increment/decrement primitives may nullify (or at least significantly decrease) the cost of locking.

    12. Re:Not many by 0x0d0a · · Score: 1

      SGI's STL has iota() and libstdc++ doesn't.

    13. 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.
  15. Major downside: VC++ support by Christopher+H · · Score: 1

    Extant versions of MS Visual C++ still don't support lots of important aspects of templates. You usually don't get bitten until you're writing your own STL-style utilities (ie just using the stuff is fairly portable). Someday MS may get their act together and make an attempt towards ISO compliance.

    1. Re:Major downside: VC++ support by Anonymous Coward · · Score: 0
      That will never happen.

      Why? Because then code written under MS Visual C++ would be portable and run on other OS's.

      Oh shit, now I've done it. The BSA will get me now!

  16. One disadvantage... by FortKnox · · Score: 1, Flamebait

    ... it isn't Java

    *rimshot*

    uh... wait,... that wasn't a rimshot... that was the sound of downmoderation... *grumble*

    --
    Good quote, too many chars. Seriously, the slashdot 120 char limit sucks!
  17. Slow compile time and horrible error messages by Anonymous Coward · · Score: 0

    It's a template based library, so it has all the problems associated with templates:

    Long compilations on most compilers, but worse is horrible error messages when you make small mistakes. Every type is a template with two or more arguementsIt happens because every type is actually a template so you get very long error messages.

    But it is still a great library, very efficient and highly expressive.

  18. Its slashdotted by Anonymous Coward · · Score: 0
  19. Re:I never learned STD by Anonymous Coward · · Score: 0

    In what ways are MFCs superior to STLs ? Pray do explain the benefits to us all... Is it just me or are MFCs 'good' for windows centric exclusively?

  20. Re:I never learned STD by Anonymous Coward · · Score: 0

    And hopefully you used condoms as well.

  21. 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 Anonymous Coward · · Score: 0

      Well, for one, string foo isn't simply a pointer, it's an actual instantiation of a string object. If you're wanting a null string pointer, try something like this:

      std::string* foo = NULL; or even better,
      std::string* foo = 0; or std::string* foo(0) even.

      If what you want is an empty string, and you want to make sure that it's empty since some compilers do things differently than others, why don't you do something like

      std::string foo("");

    3. Re:Well.. by Anonymous Coward · · Score: 0

      I'm pretty sure that the default behavior of the string class is to create an empty string (""), so there shouldn't be a need to initialize it to empty. That's what the default constructor is for :)

    4. 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.
    5. Re:Well.. by DCram · · Score: 1

      funny thing is I have seen this too. And they used the defines inside an enum.

      --
      If I were only smart enough to accomplish the things I dream about.. Or maybe too dumb to care.
    6. Re:Well.. by damn+dirty+ape · · Score: 0

      maybe you should get into the habit of initializing pointers to NULL instead.

    7. Re:Well.. by Anonymous Coward · · Score: 0

      String foo=NULL is wrong because String is an object not a simple type. Presumbly the String object's overloaded assignment opperator is allocating memory and then doing a strcpy or memcpy of the static string to the right of the operator. Now if that string is a NULL the first time it tries to read address 0x0 it will segfault. A more robust implementation might check for this but in the vein of C/C++ most code do not do bounds checking.

    8. Re:Well.. by ouslush · · Score: 1
      This is where copy constructors come in handy.


      string foo = string();


      Always use the default copy constructor for a data type if you want to set it to a null or default value.


      Note: also works like this


      int a = int();

      char b = char();

      bool c = bool();


      etc. etc. etc.

    9. Re:Well.. by Anonymous Coward · · Score: 0

      Actually,

      string foo;
      // calls the default constructor because a std::string is a class.
      // You don't need to explicitly initialize it with the empty constructor.

      int a;
      // int a = int() is unnecessary, and probably won't work on all platforms.
      // An int is not a class and subsequently does not have a default constructor.

      // same goes for the other base types eg. char, boolean etc.

    10. Re:Well.. by Anonymous Coward · · Score: 0

      These two statements are different:
      int a;
      int a();

      The first leaves the value uninitialized while the second sets the variable to zero. This is C++ standard behaviour.

    11. Re:Well.. by Anonymous Coward · · Score: 0

      Stroustrup recommends using 0 (number zero) to initialize pointer rather than NULL as NULL may be defined differently on some platforms.

    12. Re:Well.. by Anonymous Coward · · Score: 0

      Disregard the above post; it's total nonsense.

    13. Re:Well.. by Heinrich · · Score: 1

      Please get rid of NULL completely, not just in the context of a string initialization. NULL is a relict of ancient C times and it might even hit you in C++ if NULL is not 0. This is thoroughly explained in 5.1.1 in Stroustrup's book about C++.

    14. Re:Well.. by Anonymous Coward · · Score: 0

      It is you.

      string is not char*.
      It is not a pointer at all.
      So initializing it to NULL is not appropriate.
      Also, there is no need to set it to anything
      ( Your string x = ""; example... )
      If you want an empty string
      string x; is completely sufficient.

    15. Re:Well.. by ejasons · · Score: 1

      Reminds of the time I saw code where someone had

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

      This is actually good practice. You shouldn't use constants directly in your code, as you never know when the value of "TWO" might change!
    16. 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).

    17. Re:Well.. by Anonymous Coward · · Score: 0

      Unlike char * (the C legacy for strings), string ain't a pointer.
      So why initialize to NULL?

    18. Re:Well.. by Anonymous Coward · · Score: 0

      This is also pretty inefficient and one of the reasons say that C++ is slow :) When you do something like std::string foo = std::string(), you're temporarily creating _2_ string objects. There's no need for this. If what you want to do is make sure that it's initialized to an empty string (and to everyone who claims that this isn't a valid concern, you obviously haven't dealt with different compilers on different platforms that tend to do whatever they see fit :), just do something like std::string foo(""). This is more efficient since the initialization is done in the constructor of the _1_ object that you're creating now.

    19. Re:Well.. by Heinrich · · Score: 1
      Well, if NULL is not 0, then it is ((void *)0).

      But ((void *) 0) is no longer the same as 0. This difference could be critical if you assign it to a pointer. Please note that C++ compilers are free to chose another representation than all-bit-zero for pointers. If you assign an explicit 0 to a pointer, it can be treated correctly by the compiler. This, however, is no longer true if you play games with casts. That it still works on many platforms does not mean that it is correct.

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

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

  23. Going to miss Rogue Wave by Codex+The+Sloth · · Score: 1

    I used to use RW for server side stuff -- switching to STL along is a poor substitute. The string class is much poorer and the msdev STL implementation is nowhere near as good as RW. OTOH, Rogue Wave is pretty expensive (which is why most people switch away from it I imagine...)

    Good luck though!

    --
    I am not a number! I am a man! And don't you ... oh wait, I'm #93427. Ha ha! In your face #93428!
    1. Re:Going to miss Rogue Wave by tommck · · Score: 1

      Being a bit Rogue Wave ignorant, can you tell me what the problem is with "string" ?

      --
      ---- It puts the lotion on its skin or else it gets the hose again. It does this whenever it's told.
    2. Re:Going to miss Rogue Wave by Anonymous Coward · · Score: 0

      Fortunately some compilers (Borland) comes with the Rogue Wave STL. If you're building for Windows and are lucky enough not to be tied to MSVC++, Borland is pretty excellent. The STL implementation gives fewer problems than most others, and is overall a much nicer compiler to use. It also makes binaries that are easier to distribute.

  24. overhead and memory leaks by Anonymous Coward · · Score: 0

    Alot of overhead and tons of memory leaks. STL has not been tested as well as one might think...

    1. Re:overhead and memory leaks by jason_watkins · · Score: 1

      Which implimentation? STL is a standard, there are at least 50 seperate implimentations. All the ones I've used have been bulletproof.

      Don't be an idiot, think about what you post next time.

  25. Re:I never learned STD by Palidine · · Score: 1

    except of course that the MFC makes your executables the LARGEST things in the known universe. MFC is good for GUI app programming bad for everything else. It includes tons of libraries into the .exe and unless you are doing GUI you won't use most of them.

  26. Re:I never learned STD by Anonymous Coward · · Score: 0
    I never learned STD


    Doesn't that stand for Sexually Transmitted Disease?


    Also M$'s implementations of the STL are buggy and broken despite these problems being noted since release 1.0.

    M$ dislikes ALL standards they didn't create?

    Dunno....

  27. Documentation could be better. by sean-mccorkle · · Score: 1

    My limited experience with STL was pretty satisfactory, but I had a lot of trouble finding either a well-written reference or guide. There are plenty of books out there, but I had to study them pretty seriously and do a lot of learning-curve testing before I felt comfortable using the library.

    Otherwise, the STL design is pretty rational. I'll continue using it.

  28. 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 Anonymous Coward · · Score: 0

      You're describing a problem with various implementations of the STL and with various compiler vendors.

      As a standard, generic containers with complexity gaurantees is a great idea, and you've failed to point out any shortcomings in it-as-such.

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

    3. Re:the STL is imporperly named by Anonymous Coward · · Score: 0

      The benefit, though, is that if I get code that uses a vector as a stack, I don't ever have to worry that the stack is written incorrectly and I know all of the methods. For individual developers, the STL is a time saver. For developement groups, it is indespensible. The ONLY problem I have had with the STL is difficult compile error messages, and these become decypherable with experience.

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

    5. 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]
    6. 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.
    7. Re:the STL is imporperly named by rsclient · · Score: 1

      The STL is badly engineered.

      (1) Every time you design a library you get a choice of lots-of-options or make-it-simple. It best to go in one direction or another. STL tries to go middle-of-the-road, resulting in too much complexity for most jobs, but not enough for wierd ones.

      (2) Mismatching the requirements of the STL for very, very robust template handling with the real-world sucky template implementations. This leads to lots of imcompatible, almost-STL libraries, grossly reducing code reusability.

      (3) Mismatching STLs need for smart error messages with real-world compilers lousy error messages. If I see any more 1024 byte messages with the word "basic_string" repeat a couple dozen times it will be too soon.

      Note that these are engineering problems: making a dream work in the real world. The 1024 byte error messages are not STL's "fault" -- but it's STL that that triggers them, and STL that could have been designed such that when when an error is triggered, a more useful message was generated.

      Peter
      What, me bitter?

      --
      Want a sig like mine? Join ACM's SigSig today!
    8. Re:the STL is imporperly named by thomas.galvin · · Score: 1

      The topic of this thread is "What are the drawbacks to the STL", and everyone that has mentioned drawbacks to the STL has gotten moded as flaimbait. Amazing.

      What the parent said is true; the usability of the STL vaies greatly from vender to vender, compiler to compiler. I have spent hours trying to figure out what was wrong with my code, only to find ou thtat Forte had bitten FUMed me again.

      Alos, try reading a compiler error that mentions an std::vector > >;
      std:string itself expands to std::basic_string. I;m sure there was a good reason for it, but I'll be darned if I can figure it out.

      The STL sets out to do some very useful things, and by and large accompilshes that. You do, however, need to be careful about which version of the STL you are using; some are more standard than others.

    9. Re:the STL is imporperly named by thomas.galvin · · Score: 1

      And here's the HTML version(dammit):

      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.

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

    11. Re:the STL is imporperly named by Anonymous Coward · · Score: 0

      I think it's basically because they tried to make the Standard Library (which includes the string class) as flexible as possible. So you have "basic_string", which is typedef'd to "string" for simplicity. You also have 2 byte character strings for other character sets (ie, Kanji, Cyrillic, etc.), which is called something else like "w_char_string". Josuttis' book on the Standard Library does a great job of explaining this stuff.

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

    14. Re:the STL is imporperly named by Anonymous Coward · · Score: 0

      Where the blame lies is purely academic. In the real world, it effectively doesn't matter, because someone writing STL code can't ignore a compiler error or code that doesn't work just because "the standard" says it should.

    15. Re:the STL is imporperly named by Anonymous Coward · · Score: 0
      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++.

      Why not just use Common Lisp? It has a lot of users, and it has garbage collection, and macros (like templates done right). It's object oriented, too.

    16. Re:the STL is imporperly named by gkatsi · · Score: 1

      perpendicular: The preferred term is orthogonal :)

      For garbage collection, you might want to check out the boost files section and look for cyclic_ptr. It's a nice smart pointer implementation that actually handles cyclic references (that's the only thing a garbage collector can do that a smart pointer like boost's shared_ptr does not do).

      And of course, there's always Hans Boehm's garbage collector at http://www.hpl.hp.com/personal/Hans_Boehm/gc/, but I guess you were referring to something that is integrated into the language.

    17. 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.
    18. Re:the STL is imporperly named by Anonymous Coward · · Score: 0
      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++.

      The memory allocation operator 'new' can be overloaded. I wrote a Scheme interpreter in C++ and the garbage collection was performed by overloading new.

    19. Re:the STL is imporperly named by ralphbecket · · Score: 1

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


      Despite the hype and received wisdom, it should be noted that OOP has singularly failed to deliver.


      [plug]
      Take a look at the modern declarative languages (Mercury, Haskell, Clean, OCaml) to see how much easier life can be with modern languages. Mercury's foreign language interface is second to none - you can even write C/C++/whatever in-line.
      [/plug]

    20. Re:the STL is imporperly named by SLOGEN · · Score: 1
      perpendicular: The preferred term is orthogonal )

      OK. To explain the differences of "programming-styles", I often analogize to linear algebra, with programming-styles (imperative, OO, GP, functional, ...) as vectors in the space of programming-styles. which makes OO and GP "perpendicular".

      You might as well look at it as the OO and GP spaces of programs, which I would be inclined to say are orthogonal in the space of programs...

      ...smart pointer implementation...

      I'm aware of the boost libraries, and i especially like (and use) the boost::function stuff...

      One problem with "smart pointers" is, that there's one for every library... and the complexity involved in getting pointers to members, pointers to member functions and that stuff working properly (I have done it, of course :)

      The most obvious problem are:

      1. performance. smart pointers MUST perform action on every copy of a reference, thus making garbage collection rather expensive... stop-and-copy only cost something when you GC, and the cost is linear in the used memory.
      2. conversion. Converting between different smart-pointers is not possible, and to normal pointers mostly invalid

        My shared_ptr<foo> cannot be used as a cyclic_ptr<foo, and the expenses of just having every pointer implemented as cyclic_ptr<> are often too big because of the above performance problem. This problem becomes insurmountable when using third-party libraries!

      3. error messages. BOOST does a good job of error-reporting, but the error-messages that a smart-pointer can generate are inherently worse than the compiler error messages for pointer usage.
      http://www.hpl.hp.com/personal/Hans_Boehm/gc/, but I guess you were referring to something that is integrated into the language.

      I tried out BoehmGC, and it work's OK quite a lot of the time, but it never worked as smooth as a OO-standard-language GC :)

      I generally oppose extending a language with "new" features, unless they are accepted and proven in other langauges (don't think chiken and egg, this strategy will work :), but I think GC has proven it's worth...

      --
      SLOGEN [ http://ungdomshus.nu : Sebastian cover music]
    21. 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.

    22. Re:the STL is imporperly named by epine · · Score: 1


      No, unfortunately the STL could not have been designed that way, because the standardization commitee exempted diagnostics from their mandate from the outset. This was before templates were a vital feature of modern C++ and a bad call in retrospect IMHO. However, they had so much trouble finishing off what they did have on their plate that adding another dimension might have sunk the entire enterprise.

      The "middle of the road" that the STL strives to achieve is suitability to professional 3rd party library vendors, somewhat randomized by time pressures.

      The feeling was that the majority of programmers should be programming on top of application specific libraries not the raw STL itself (although that is intended to be viable where it makes sense to do so).

      People come to strange ideas about what C++ was trying to achieve by looking at it from the point of view of "one stop shopping". Rather than providing convenient solutions for every need at the bottom layer, they focussed on making it possible to provide good solutions in the intermediate layers.

    23. Re:the STL is imporperly named by sir99 · · Score: 1
      Just to nitpick ;)

      OK. To explain the differences of "programming-styles", I often analogize to linear algebra, with programming-styles (imperative, OO, GP, functional, ...) as vectors in the space of programming-styles. which makes OO and GP "perpendicular".

      "Orthogonal" is the multi-dimensional extension of perpendicular. A set of vectors is orthogonal if and only if the dot-product between each pair of vectors is zero. (/me wonders what set of programming languages (vectors) would form a basis for the vector space containing all programming languages)

      --
      The ocean parts and the meteors come down
      Laid out in amber, baby.
    24. Re:the STL is imporperly named by gkatsi · · Score: 1

      Regarding conversion at least, there have been some interesting discussions lately on the boost list (in part in response to the requirements set forth by the meeting of c++ working group in Curacao).

      One of the suggestions was a traits-based smart pointer. Since you would have only one smart pointer class, which modifies its behavior based on the type it points to, there would be no conversion issue. Of course, without having read the discussions in detail, it seems to me it limits you to one type of smart pointer per type.

      You may also want to consider whether you really want to convert between a shared_ptr and a cyclic_ptr. They handle the memory differently and while a cyclic_ptr may decide to delete an object, a shared_ptr will not know it.

      If you're talking about interfaces, this problem can be solved if you make the functions (member or free, does not matter) and the classes take template arguments and use a policy-based smart pointer. I'm talking about something like:

      template(typename T, typename P)
      void foo(smart_ptr(T, P));

      instead of
      template(typename T)
      void foo(shared_ptr(T));

      (where P is an aggregate of all the policies for your smart pointer)
      (replace parentheses with less-than and greater-than)

      As for error messages, I think we need to wait a bit for these things to become standardized enough that compilers can detect (mis-)uses of them and report appropriate, clear error messages.

    25. Re:the STL is imporperly named by SLOGEN · · Score: 1
      Regarding conversion at least, there have been some interesting discussions lately on the boost list (in part in response to the requirements set forth by the meeting of c++ working group in Curacao).

      Those boost guy's rock, the boost::function is GREAT. I'll need to read up on their comments.

      You may also want to consider whether you really want to convert between a shared_ptr and a cyclic_ptr. They handle the memory differently and while a cyclic_ptr may decide to delete an object, a shared_ptr will not know it.

      That's the problem! I have to specify if my method takes a cyclic or a shared (or auto or simple) pointer... and there's no (sane) way to convert.

      template(typename T, typename P) void foo(smart_ptr(T, P));

      Nice workaround, but no cigar... this prevents virtualization:

      struct Foo {
      virtual void bar(Baz*);
      }

      Now with shared or cyclic or whatever:

      struct Foo {
      virtual void bar(shared_ptr<Baz>);
      }
      But the trick:
      struct Foo {
      template<typename P>
      virtual void bar(smart_ptr<Baz,P>);
      }
      doesn't work (of course). And what we REALLY don't want is:
      template<typename P>
      struct Foo {
      virtual void bar(smart_ptr<Baz,P>);
      }
      compile-time type-parameters and virtualization don't mix (very well).
      --
      SLOGEN [ http://ungdomshus.nu : Sebastian cover music]
  29. STL incomplete - needs Join by j_dot_bomb · · Score: 1

    I find that much code I want to write requires database-like functions like join. I dont mean that it requires any of this necessairly written to disk. STL has all sorts of ways of indexing to speed up searches and inserts and do it cleanly. But then it misses the next key step which is join.

    1. Re:STL incomplete - needs Join by jason_watkins · · Score: 1

      Nothings stoping you from writing it. If you're talking about the intersection of two containers, it would be fairly simple to code in a few lines. Made into a robust reusable thing, not much longer.

      You misunderstand the situation. STL, and C++ is not like SQL. You are not given a fixed set of functionality. You are free to write anything you need.

    2. Re:STL incomplete - needs Join by JonK · · Score: 1

      Erm... set_intersection does precisely this, and in one line too...

      --
      Cheers

      Jon
    3. Re:STL incomplete - needs Join by gkatsi · · Score: 1

      The view template library, at http://www.zib.de/weiser/vtl/ provides all the database-like operations you would want. But it is only a first attempt at the design of such a library, so I think that there is already something else in the works that supercedes it.

  30. The STL is pretty good by xiox · · Score: 1

    Once you've got used to it, the STL is a great productivity booster. No more writing those generic data structures. I'd say anyone using C++ who doesn't know the STL is missing out on a large chunk of useful knowledge. Unfortunately it takes a long time to master it (I haven't reached that stage yet!).

    Problems? I find that executables can become quite large if you use the templates all the time, without thinking how large the code for all these classes can be. You have to think about using vector<T*> rather than vector<T> (vector<T*> is specialised).

    Another problem can be the warnings from compilers. gcc-2.95 has awful warnings for errors in using templates. It's good to have a modern compiler (e.g. gcc-3.1), which doesn't leave you with an awful mess of < < blah > blah >. This is a general problem with C++'s template syntax, which can become very messy! I'd love a language which really cleaned up C++'s syntax generally.

    1. Re:The STL is pretty good by Razorviro · · Score: 1

      If you want to use a programming language like C++ with much improved syntax, than try Java. A lot of people complain that Java is too slow, the truth is that a lot of the times Java is equal if not better speed wise. One of the best things about java is that you only have to write you source code once. Java works on a lot of platforms too. As long as a platform has JVM, java code can run on it.

    2. Re:The STL is pretty good by Anonymous Coward · · Score: 0

      > If you want to use a programming language like C++ with much improved syntax, than try Java. A lot of people complain that Java is too slow, the truth is that a lot of the times Java is equal if not better speed wise. One of the best things about java is that you only have to write you source code once. Java works on a lot of platforms too. As long as a platform has JVM, java code can run on it.

      Come back after you've written a reasonable Java program (like a Swing GUI), tried to actually run it on several platforms, and had to sort out the different implementations of Java on those different platforms. Said differences requiring source changes in order to run correctly.

      ..just like many people here have said about the STL. It's *not* "write once, etc", not yet.

  31. STL migration by roberto0 · · Score: 1

    As far as I can tell, STL is supposed to be standardized, but there are different implementations out there. You must always be wary when migrating your code. Different compilers will implement the STL, well, differently. This basically means that you'll always have to debug and test your code on every OS and with every compiler.

    Another drawback is that STL methods don't parallelize that well.

    --
    Those who can, do. Those who can't, simulate.
  32. 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 thomas.galvin · · Score: 1

      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.

      Typedefs are the work of the devil himself. I have spent way too long searching through header files to find out someone decided it would be a good idea to typedef std::vector<std::dtring> to string_list.

    7. Re:Not many drawbacks by emarkp · · Score: 1

      I meant to add that the std:: can be removed with "using" but I forgot. In our project we're migrating from classic streams (e.g., istream.h) to standard streams (e.g. istream), which makes it imperative to not sprinkle "using" directives around, especially in headers.

    8. 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));
    9. 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.
    10. Re:Not many drawbacks by HopeOS · · Score: 1

      So you're the guy who wrote this!? There couldn't be more than one out there.

      std::map<std::string, std::vector<std::string> >::iterator i = m_dict.find(std::string(key));

      Thank god for typedefs. Life's hard enough with multi-line error messages.

      -Hope

    11. Re:Not many drawbacks by joshwalker · · Score: 1

      Most experts will tell you never to use using directives or use declarations in header files, since you can't always predict the environment they will be used in. In your source files, however, it doesn't matter so much, and you can use whatever you're comfortable with.

    12. Re:Not many drawbacks by joshv · · Score: 1

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

      Hmmmm... Someone should talk to Sun about these coding standard. Try:

      import java.util.*;
      import java.sql.*;
      .
      .
      .
      Date sellDate = new Date();

      Won't compile. Always bugs the hell out of me... I defy you to come up with a way of getting around this that doesn't either added tons of new more specific imports at the top of the code, or force you to write out java.util.Date all over the place. Thanks Sun.

      -josh

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

    14. Re:Not many drawbacks by oever · · Score: 1

      Isn't that what #include is for? The whole using keyword seems useless to me. Unless there would be a stopusing.

      --
      DNA is the ultimate spaghetti code.
    15. 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.
    16. 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

    17. Re:Not many drawbacks by JonK · · Score: 1
      To summarise the (correct) comments above: use
      using std::type;
      declarations to import specific std:: types in your header files, which is where you really need to avoid namespace clashes which may occur down the line as users combine your libraries with other peoples', but you can safely use
      using namespace std;
      declarations in the body of your code, since this isn't going to be #included anywhere else
      --
      Cheers

      Jon
    18. Re:Not many drawbacks by David+Greene · · Score: 1
      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.

      This is a known problem in the STL. As some gurus have put it, "STL is not STL enough." What that means is that the STL falls short of using the full power of templates. Check out the Boost bind library (and later, the Lambda Library) for a solution to the for_each problem.

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

      std::vector::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.

      typedef makes this a non-issue. I find the "wordiness" a nice form of in-code documentation.

      unexpected results: Understand the difference between remove() and erase() in the containers.

      It's unfair to label this "unexpected," but you're right in that knowledge of the API is important. As it is for all libraries.

      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.

      This is the real power of the STL. IMHO too many people concentrate on "containers of X." This goes doubly for the C++ template engine as a whole.

      I recommend reading the first part of Generic Programming and the STL. It'll help you undestand the thinking behind the design.

      Then get Modern C++ Design , join the Boost mailing list and take it to the next level.

      The STL is great. Some of the stuff coming in the next library standard revision is even better. The stuff in Boost is outstanding.

      The biggest problem I have had with the STL is convincing people to use it. The available implementations could be better (smaller, more template specialization, etc.) but the savings in programmer time is well worth the slight cost.

      --

    19. Re:Not many drawbacks by Anonymous Coward · · Score: 0


      not placing "using" statements in headers is a rule to follow absolutely. Why ?
      because headers are a declaration place, and when you declare things, you need to be as precise and clear as possible.

      Please excuse my poor english.

    20. Re:Not many drawbacks by Anonymous Coward · · Score: 0

      Forgive my ignorance of the whole STL and C++, but why is it that virtually all comments involved seem to revolve around three things: type, garbage collection, and container interface. Scheme handles all three well, though it's not a strictly typed language. In all actuality, I'm quite confused why C++ is heading towards a scheme language including functions like map, for-each, etc. Just use scheme people. You can even do for-loops, of a sort. Anyways, whenever you figure out what you really want to do, why not just use another language that already supports most of what you need...

    21. Re:Not many drawbacks by gkatsi · · Score: 1

      Not so magically. If you consider all the operations that lists support but vectors don't (and vice versa), pretty much all you can do with code that converts "magically" between list and vector is iterate using begin() and end(). No constant time insertions and removals at any place, no modifications without invalidating iterators (list), no constant time access to any element in the container (vector) and more.

    22. Re:Not many drawbacks by Anonymous Coward · · Score: 0

      When I think about the STL, I get a boner. I know you do too. It would be nice if we could sit together
      and talk about the STL, then you could stroke my boner. I'd stroke your boner too. It would be fun.

    23. Re:Not many drawbacks by Anonymous Coward · · Score: 0

      import java.util.*;
      import java.sql.*;
      import java.util.Date;

      This is not exactly a difficult problem to solve. The other name collision that comes up frequently is between awt List and util List.

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

    25. Re:Not many drawbacks by Anonymous Coward · · Score: 0

      That about sums up the STL, I think.

    26. Re:Not many drawbacks by Anonymous Coward · · Score: 0

      #define struct union

      is even better

    27. Re:Not many drawbacks by Anonymous Coward · · Score: 0

      I've been known to do that in unit test code that performed whitebox testing:
      #define private public
      #include "someheader.h"
      ... do tests that access private members ...

      However, I'd better not ever catch anybody doing that in shipping code...

    28. Re:Not many drawbacks by epine · · Score: 1


      It wouldn't be very hard to write an include file that undefs all C++ keywords.

      #ifdef private
      #undef private
      #endif

      and so it goes

      The war might escalate, but the pedants will still win.

    29. Re:Not many drawbacks by epine · · Score: 1

      None of the STL books recommend thinking about the different containers as interchangable.

      Every pair of containers has significantly different semantics. The only pair where this might make sense is vector/deque if front insertion is not required. deque has the advantage of never copying your objects from one place to another behind the scenes. If object copies are expensive, deque is often faster than vector. deque is the default storage for the stack adaptor.

      It's still a good practice for application classes to supply their own iterator typedefs.

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

      Is it allowed to do something like

      #define undef #define HAHAHA \/\/

      ;-)

      -Paul Komarek

    31. Re:Not many drawbacks by gkatsi · · Score: 1

      I did not say that someone recommended that. I'm sure even the original poster did not mean to recommend it. But it is possible that someone can misinterpret that post, that's why I replied.

      Besides, many novices often make the mistake of thinking that containers _are_ interchangable like that and they end up learning the hard way that they are not.

  33. Memory Management by keird · · Score: 1

    Here's my only beef with the STL: memory management. I've run into many situations where the STL memory manager just won't seem to release memory, especially in the string class. Now, it could have been the specific implementation that I was using, but I've seen many others with the same issue.

    1. 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));
    2. Re:Memory Management by tommck · · Score: 1
      Do you frequently load massive amounts of strings, then manipulate their contents and leave them in memory? Or are you quibbling about a few K of memory?

      T

      --
      ---- It puts the lotion on its skin or else it gets the hose again. It does this whenever it's told.
    3. Re:Memory Management by keird · · Score: 1

      I really had a problem in a multi-threaded server that I had written. It seemed that if I would connect a lot of users(which caused a lot of allocations) then after they disconnected the memory usage for the app would stay constant. Subsequently, if I connected with fewer users the memory would be constant. But, if I connected with more users than the first time, then the memory would increase by the difference. Strange, huh? Not a memory leak issue because otherwise the memory usage would always grow. It just seemed that STL would not reclaim memory. I finally started migrating most of my structures away from STL and it alleviated the problem.

    4. Re:Memory Management by salotia · · Score: 1

      This is probably because, as you suspect, most STL implementations use a custom allocator for memory allocations which NEVER releases memory to the system. When objects destruct, it places this memory on a free-list and then attempts to reuse it later.

      This increases performance for multithreaded apps, but has the obvious disadvantage that if you had to handle one request that used up a large amount of memory, your server will not release that memory to the OS until the process exits.

    5. 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
    6. Re:Memory Management by Anonymous Coward · · Score: 0

      You do realize that one of the template arguments on all of the STL containers is an allocator? If you don't like the behavior of the standard allocator, use any allocator you want. This sort of flexibility is what the STL is all about.

    7. Re:Memory Management by Anonymous Coward · · Score: 0
      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.

      You don't have to! This is exactly why the STL is designed to be used with any allocator you want. The second template argument on all of the STL container classes is the allocator. It's only defaulted to the standard allocator. You don't have dig through header files to find what you're looking for, just pass the allocator you want to use in as a template argument.

    8. Re:Memory Management by Anonymous Coward · · Score: 0

      I am currently working in the games industry where we are - at present - doing in-house ports between different platforms. We've had little problem with STL on the PC, given that PCs tend to have plenty of RAM and if needs be the OS will shuffle programs between virtual memory and physical RAM without too much problem.

      Our problem comes when we hit another platform such as PS2 (and Gamecube would be worse) which has only 32MB of RAM available for the whole program - sans video and audio RAM. The problems we are seeing here is that with our current compiler setup the memory management is at bet poor and so we've written a map of RAM to see what's happening. The result is that we get STL smattering RAM all over the place and then ellecting to not free it up. The net result being that eventually the STL memory fragments the RAM to such an extent that we cannot reliably allocate large blocks; such as for video playback.

      Okay we could pass in another allocator, but at this stage it's not really viable, we might as well strip the STL that we can strip easily.

      The major problem we have had with this port has been not so much that STL is slow, but that it is FAR TOO EASY to use it and especially for games programming, you CANNOT allow yourself to become sloppy or lazy with the use of STL. Sadly we were advised to use it and the use of it became abuse of it. This is one thing to watch.

      And in particular response to this thread if you ARE using the STL within a platform which has fixed RAM and relatively low RAM. Expect your RAM to become fragmented and expect to want to be able (where games are concerned) to load your menus, load your level, unload your level and not have the same figures of RAM allocated after your level unload as you had prior to loading. Use your own allocator here at developement time and you'll save yourself a LOAD of hastle during the port.

      Another thing, the PS2 HATES the STL. So beware and be warned!

      Cheers
      Ian

  34. Rimshot emoticon by geophile · · Score: 2

    Here it is, an ASCII rimshot:


    \/!


    This is my invention, which is mine.

    1. Re:Rimshot emoticon by Anonymous Coward · · Score: 0

      > Here it is, an ASCII rimshot:
      > \/!
      >This is my invention, which is mine.

      Go ahead and patent it, then; certainly no one at the USPO will stop you :-).

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

    2. Re:Cross-platform compatibility is a pain by Anonymous Coward · · Score: 0

      I concur. I've written myself quite a few utilities, and ported even more utilities and games. I've never had a problem porting STL code BECAUSE 3D GAMES AND UTILITIES DON'T USE STL!!!!!

  36. 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 Anonymous Coward · · Score: 0


      - Never use vector! It's a horrible specialization and is not even a container. Very, very bad.


      Are you talking about vector of bool (ie vector<bool>)? It looks like part of your message got whacked.

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

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

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

      I misspoke. vector is the boogeyman.

    5. Re:Check out "Effective STL" by Myers by Anonymous Coward · · Score: 0

      Never use vector?
      vector is an STL sequence container.
      The only aspect of vector that may be considered a horrible specialization is vector<bool&gt. vector<bool> is a specialization and doesn't meet the requirements of section 23.1 of the Standard for being a STL container. This is addressed in Meyer's Effective STL (which is a great book). It makes good sense to use a vector in other situations. In fact, Myers calls it the "default" sequence container to use.

    6. Re:Check out "Effective STL" by Myers by SLOGEN · · Score: 1
      - Never use vector! It's a horrible specialization and is not even a container. Very, very bad.

      I object.

      1. You don't need to let anybody know that you are using a vector, just use typedef to expose iterators.
      2. A vector is good when
        1. you have an idea about how many items will be inserted into a linear structure or
        2. you require constant lookup, and are willing to sacrifice linear internal delete time (which is often the case when you'll delete all items at the same time)
      3. unfortunatly: std::hash_map<size_t,T> is not an option yet :)
      4. Yes, it's a specialization of list, but most datastructures are specializations which allow certain operations to be performed fast, at the expense of others.

      Just use a typedef to hide that your actually using a vector

      - Allocators are for the most part evil. Be very wary of them.
      I would rather say: Ignore them -- don't think about them, unless you are in embedded systems.
      --
      SLOGEN [ http://ungdomshus.nu : Sebastian cover music]
    7. Re:Check out "Effective STL" by Myers by MobyDisk · · Score: 2

      What is wrong with vector ?

    8. Re:Check out "Effective STL" by Myers by emarkp · · Score: 1
      The MSVC STL was unchanged in v.5 vs. v.6. It's much better in v.7, however you have been able to purchase an updated version at http://www.dinkumware.com for a while. See http://www.dinkumware.com/libcppvc.html for details.

      Yes, vector<bool> was a horrible mistake. That should be fixed in the next version of the standard. Where performance is important, use vector instead.

    9. Re:Check out "Effective STL" by Myers by Anonymous Coward · · Score: 0

      Victor.. We all hate 'im ;*)

    10. Re:Check out "Effective STL" by Myers by GuavaBerry · · Score: 1

      I believe what you mean is never use vector<bitset>,

      Actually, what he meant was:

      Never use vector<bool>. It's an Item (18, glancing at my copy) covered in the Meyers book he plugged (in summary: it's not an STL container, and it doesn't contain bools).

    11. 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
    12. Re:Check out "Effective STL" by Myers by bertok · · Score: 1
      Never use vector! It's a horrible specialization and is not even a container. Very, very bad.
      Why? It IS a container, and IMNSHO it's the single most useful class in the entire library! With it, you'll never have to allocate your own array again.
    13. 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));
    14. Re:Check out "Effective STL" by Myers by epine · · Score: 1


      That's a good explanation of what happened.

      The analysis of the predicament that vector creates is a deeper matter.

      It's the STL algorithms that enforce the requirement that &*iter always be a valid expression. What this means is that the STL algorithms are not officially capable of working with proxy iterators, unless the proxy iterators are iterating over a manifest representation.

      People apply STL algorithms to proxy iterators all the time and get away with it because very few algorithms actually take the element address which they are entitled to take.

      Properly speaking, the STL algorithms should be referred to as the STL container algorithms, because they promise to work when given iterators with container semantics (that every element has an address in memory).

      This makes the STL algorithms far less generic than they pretend to be. vector ends up taking the flak for pointing out a defect in the genericity of the STL algorithms. The failed experiment ended up in the C++ standard because too many people involved presumed that the STL algorithms promised a higher degree of genericity than the standard officially permits.

      A principled solution to this problem would be to extend iterator traits to allow algorithms to determine whether reference semantics exist for the iterators supplied and act appropriately. This would greatly increase the formal genericity of the STL algorithms.

      One could also define an element adaptor such as this:

      vector > V;

      and specializations for the containers such that:

      template
      Contain >

      provides a container interface with no reference semantics.

      OK that's mostly a joke.

      There are many classes that people might wish to implement thinking they are container classes, but which are unable to provide reference semantics.

      I tend to think of containers with reference semantics as strong containers and synthetic containers lacking reference semantics as weak containers. Weak containers should be able to supply iterators to the vast majority of algorithms.

      The problem with the vector specialization as defined is that it specializes a strong container into a weak container. This is definitely wrong. But not nearly as wrong as the presumption made in the algorithms that all iterators supplied have strong container semantics.

    15. Re:Check out "Effective STL" by Myers by epine · · Score: 1

      **** REPOST with BROKETS RESTORED ****
      Dang it, plain old text is not so plain after all.

      That's a good explanation of what happened.

      The analysis of the predicament that vector<bool> creates is a deeper matter.

      It's the STL algorithms that enforce the requirement that &*iter always be a valid expression. What this means is that the STL algorithms are not officially capable of working with proxy iterators, unless the proxy iterators are iterating over a manifest representation.

      People apply STL algorithms to proxy iterators all the time and get away with it because very few algorithms actually take the element address which they are entitled to take.

      Properly speaking, the STL algorithms should be referred to as the STL container algorithms, because they promise to work when given iterators with container semantics (that every element has an address in memory).

      This makes the STL algorithms far less generic than they pretend to be. vector<bool> ends up taking the flak for pointing out a defect in the genericity of the STL algorithms. The failed experiment ended up in the C++ standard because too many people involved presumed that the STL algorithms promised a higher degree of genericity than the standard officially permits.

      A principled solution to this problem would be to extend iterator traits to allow algorithms to determine whether reference semantics exist for the iterators supplied and act appropriately. This would greatly increase the formal genericity of the STL algorithms.

      One could also define an element adaptor such as this:

      vector<unreferenced<bool> > V;

      and specializations for the containers such that:

      template <template Contain, class T>
      Contain<unreferenced<T> >

      provides a container interface with no reference semantics.

      OK that's mostly a joke.

      There are many classes that people might wish to implement thinking they are container classes, but which are unable to provide reference semantics.

      I tend to think of containers with reference semantics as strong containers and synthetic containers lacking reference semantics as weak containers. Weak containers should be able to supply iterators to the vast majority of algorithms.

      The problem with the vector<bool> specialization as defined is that it specializes a strong container into a weak container. This is definitely wrong. But not nearly as wrong as the presumption made in the algorithms that all iterators supplied have strong container semantics.

  37. 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
  38. well thats easy by Anonymous Coward · · Score: 0

    Well obviously c++ is not c so it is not the One True Language and there for totally sucks ass and is just trash. C is The One True language and any innovative open source hacker knows c is the greatest and should be used for the rest of eternity and if you disagree i will declare a fatwah on you.

    please not the sarcasm. thanks.

  39. Potential code bloat by Christopher+H · · Score: 1

    Extensive use of templates can result in substantial executable code expansion. If you know what you're doing you can mitigate this by sharing code between instantiations. Like other time/space tradeoffs in C++ it requires the exercise of programmer judgement.

  40. Templates can get really, really, really ugly. by Anonymous Coward · · Score: 0

    Template code can be the most obscure, insanely ugly code imaginable.

    So much so that I believe it's not worth it for most of the uses people have in mind. Fact is, if you can't read, you can't fix the bugs, you can't maintain code someone else wrote, etc.

    And in my experience there are some really hot-shot C++ gurus who can look at any C++ code and instantly know exactly what it means and whether it's written correctly or has fallen into one of the (many) C++ legalistic potholes. But I don't believe your average C++ programmer falls into this category. As soon as you get beyond the trivial uses for templates you get into code that is inherently prone to error simply because correctly writing it is very difficult, mistakes and mistaken assumptions or understanding become common, etc.

    If you don't agree with this assessment, just go look at the STL code yourself. It's template code, so you get to see the sources. Now, if you could actually implement that yourself, then you are one of the gurus I mentioned earlier. If you couldn't, and be honest with yourself, then you are playing with stuff you don't truly understand, and that is a recipe for disaster.

    As Brian Kernighan once said, debugging code is inherently twice as hard as writing it, therefore if you are writing code that is as hard as you know how, by definition you are not smart enough to debug it.

    This is true for C++, in fact I'd argue it's not even just doubly true, it's triply true.

    1. Re:Templates can get really, really, really ugly. by Anonymous Coward · · Score: 1, Insightful

      the whole point of c++ is so even non-gurus can use good implementations of standard stuff...

    2. Re:Templates can get really, really, really ugly. by Anonymous Coward · · Score: 0

      No, the whole point of C++ is so you can put in a bastardization of any language concept that's occurred to Stroustrup et al.

      While the STL concept is to provide good implementations of standard stuff, the fact that this material is implemented in C++ simply obfuscates the matter to the point where error message are unreadable, unresolve symbol errors take three whole lines just to specify which symbol it is, and the implementation of the STL in C++ is so horrifying to any but the smartest gurus that if that doesn't scare you off, nothing will.

      For something like a graphics library I'd think sure, get a good implementation, document it well, and your average programmer can use it without having to be smart enough to implement it themselves. But with a C++ template library, I'm firmly of the opinion that if you couldn't implement it yourself, you are playing with fire.

    3. 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.
  41. Overhead by Anonymous Coward · · Score: 0

    STL is good, but realise the limitations. STL can only store objects, not pointers, unless you write a class to wrap the pointers (Simlar to a smart pointer class). Therefore to add something to a list a copy is made. Thats why copy constructors are necessary. You do know the difference between a deep and a normal copy ?

    They are useful, good knows we don't anyone to write another linked list class, but lots of copying can go on behind the scenes.

    Welcome to C++

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

    2. Re:Overhead by Anonymous Coward · · Score: 0

      Like I said, you can't store the pointer directly, you have to wrap it !

  42. Downsides? not a lot phisically by tandr · · Score: 1

    more mentally

    from my expirience

    a. Management heard that it is bloated, not readable etc -- you will have HARD TIME to get permission to use it.

    b. Not all programmers are equal - if somebody does not understand your code, they will try to make look like all the bugs are came from this particular code. See a. as well.

    c. If there is even a slight possibility that this platform is not support some standart feature (old compiler, etc) you better know it in first place so b. will not led to a.

    All other things like code bloatness etc -- well, if you write embedded app, you better be carefull. YMMV, you know...

  43. Re:I never learned STD by emount · · Score: 1

    Okay, thanks Bill. Another drone with the M$ blinders on that will never look at another API.

  44. 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 jason_watkins · · Score: 1

      WTF are you talking about? Unless you're using a dodgy implimentation, I'd take STL's code over some random wankers any day.

      STL is all about _free_ abstraction. You do pay for longer compile times, but c++ templates well applied can offer blistering speed.

    5. Re:Partial List by Anonymous Coward · · Score: 0

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

      ? One of the big selling points of the STL was that you'd get both; STL was supposed to already be nicely optimized (inlines in header files, etc) so using it wouldn't cause any performance hits.

      What kinds of hits are you seeing?

    6. Re:Partial List by ignavus · · Score: 1

      Really, I think the best advice I can give is this: get to really know an API before you start to use it

      Here is some more "really helpful" advice: Be perfect. Never make mistakes.

      My point is: you can only "get to really know an API" because "you start to use it" beforehand.

      I don't know anybody who really knew something before they used it.

      Perhaps what you really mean is: using C++/STL competently takes a lot of time to learn, and you will make many mistakes along the way. Don't start out by writing air traffic control or heart monitoring software for use in production sites. Or if you do, let me which hospitals/airports use your software.

      Perhaps another piece of advice: consider other languages/libraries that do not take as long to learn.

      This is one of the real downsides to the STL - the complexity. Not all projects need it. Mac software (OSX) can get by without it. Do PC software projects really need it? The answer need not always be "yes".

      --
      I am anarch of all I survey.
    7. Re:Partial List by SLOGEN · · Score: 1
      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.
      • All containers support the iterator paradigm.
      • Containers with linear ordering from 0-n and efficient indexing support integer indexing.
      • std::map support syntax reminding associative array's (operator[]) because a map is an assiciative array.

      What's there to be in doubt about?

      Of course, that's just my opinion, I could be wrong

      That is possible :)

      --
      SLOGEN [ http://ungdomshus.nu : Sebastian cover music]
    8. 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,

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

      I object.

      1. Your own "myString" is not accepted as input by any other code. You will get problems with memory ownership. Other people must use hours to try to figure out exactly what myString is good for :). Proxy'ing usually leads to ownership problems in C++.
      2. If you miss functions, why not define them?
        std::string my_obscure_missing_api_stuff(const std::string& s) { ... }
        std::string& my_mutating_api_stuff(std::string& s) { ... }
        With reasonable names of course.

      I dont't think that you really "get" the Standard Library, but you try to bend it into your "old" way of programming. One example:

      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.

      Well, the C++ standard comitee voted otherwise :)

      You can nicely expand API's in C++. just define functions outside class scope:

      template<typename T, typename A>
      horribly_missing_method(std::vector<T,A>&amp ; myargs...){
      // (above: not C++ "...", just more stuff :)
      // do the stuff (in terms of the public API)
      }

      Of course vector should not have a "size_type get_index_for(const T& t)" operation, if you need such an operation, you should probably use another data structure. But you can use the STL algorithms to easily write your get_index_for function.

      --
      SLOGEN [ http://ungdomshus.nu : Sebastian cover music]
    10. 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.
    11. 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.
    12. Re:Partial List by SLOGEN · · Score: 1
      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.

      I don't agree.

      People who use functors usually come from functional programming, and this style is suitable for use for many "odd-jobs" where C++ is not flexible enough. You don't need, or even want to give a name to all functions. For example, predicates, for std::count_if.

      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!
      Named functions and Lambda's have each their use. Don't underestimate the power of the lambda :)
      Other than something like sprintf - a major pain in the butt to get working in STL, in my opinion.

      If you are using *printf*() functions in C++, you are WAY off track. The "..." arg-style is the single most horrible thing in C, and should never had existed. Use the overloaded operator 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.)

      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.

      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.

      That is incorrect. You may use typedefs.

      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.

      Shared library of functions acting on class'es through their public API.

      And I'm not saying you should make myVector, 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.

      Composition (which you call Has-A) is more versatile than specialization (which you call Is-A), but there's no reason not to use the C++ language to obtain best results. Private inheritance provides encapsulation, efficiency and ease of implementation in many places where one class is implemented directly in terms of another.

      struct myStringVector:
      private std::vector<std::string> {
      //^^^^^^^
      private:
      typedef std::vector<std::string> implementation;
      using implementation::begin();
      using implementation::end();
      using ...;
      }

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

      --
      SLOGEN [ http://ungdomshus.nu : Sebastian cover music]
    13. 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.
    14. Re:Partial List by SLOGEN · · Score: 1
      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.
      Why would you even use an integer offset into a vector?
      for ( mylist::const_iterator it(l.begin());
      it != l.end();
      ++it ) {
      do_stuff_on(*it);
      }
      for ( mylist::size_type i = 0;
      it != l.size();
      ++i ) {
      do_stuff_on(l[i]);
      }

      If you really want to call vector::erase() just:

      l.erase(l.begin()+i))

      How hard is it?

      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.

      The methods or containers do not change paradigm, you just think, that because some (rather old-fashioned and wierd) specialization (integer indexing on vectors) work for one method, it'll work for all the methods that usually take iterators.

      The container index paradigm in the standard library is iterators -- everywhere!

      vector::erase() CANNOT take an int, because that would make many call's to erase ambiguous.

      My first foray into this was to try to erase the first character in a string. I sent 0 to string::erase

      You even had bad expiriences with (a related) ambiguity.

      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.

      The way methods that manipulate containers work is using iterators, that IS the obvious way.

      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*

      Here you touch on one of the (i think) fundamental flaws in C++, auto-conversion! and the fact that no seperate notation for a multi-convertible pointer exist. Unfortunate but true.

      --
      SLOGEN [ http://ungdomshus.nu : Sebastian cover music]
    15. 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.
    16. 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)

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

    19. Re:Partial List by SLOGEN · · Score: 1

      I think we agree more than I thoght at first. I may have misinterpreted your "Has-A" statement, thinking that you wanted to use composition whenever possible, even for usage -- as in your string example.

      In C++, inheritance (unfortunatly) plays a may roles

      1. sub-typing, or is-A (which many OO-fanatics dont' regard as seperate from specialization)
      2. specialization, or extension
      3. shared implemetation (private inheritance)

      I understand (now), that you resist using specialization unless there really is a reason..., and I agree with that.

      I am also under the impression that you argue against using the "shared implementation" idiom? This I cannot understand.

      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.

      I understand the value of implentation (and data) by proxy, and sometimes does this. But std::string is a central part of C++, and the reason it's standard is, so that people can share the definition.

      I would like to add, that I (like you) also get frustrated at the ineptitude of many people trying to do OOP. When i see:

      class Pupils: public std::set<Pupil> {
      const School& school;
      ...
      };

      My toes cruble :). Why pretend that Pupils are a set? Here I would use:

      class Pupils: {
      private:
      typedef std::set<Pupil> Collection;
      Collection collection;
      const School& school;
      ...
      public:
      Pupils& insert(const Pupil& o);
      }

      Or at least:

      class Pupils: private std::set<Pupil> {
      private:
      const School& school;
      public:
      using insert;
      ...
      }
      --
      SLOGEN [ http://ungdomshus.nu : Sebastian cover music]
    20. Re:Partial List by SLOGEN · · Score: 1
      std::vector myStringVector; Port that to Pascal, or Java, or Python. Or any other modern language.

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

      In Pascal, Java and Python, there are no type parametrisation, so you would either

      1. use the langauge's standard data-structure resembling a vecor. i.e (in JAVA):
        Vector myStringVector = new Vector();
        You would have to cast the extracted values all the time, but that's what you loose from not having type-parameters.
      2. Write your own StringVector, (probably in terms of vector)
        class MyStringVector {
        private Vector v;
        String get(int i) { return (String)v.get(i); };
        }

        Notice, that the MyStringVector cannot possibly specialize any of the JAVA collections, since the interface is (by design) stricter.

      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.
      Of course typedef's ecapsulate (unless people actively circumvent it):
      class Foo {
      private:
      typedef map<Bar,Baz> FooMap;
      FooMap m;
      public:
      typedef FooMap::const_iterator const_foo_iterator;
      const_foo_iterator begin() const;
      const_foo_iterator end() const;
      }

      Now, Foo can change it's implementation of the FooMap without users of Foo having to rewrite code. If users write:

      map<Bar,Baz>::const_iterator foo_it(foo.begin())
      Then, of course, the encapsulation is broken, but luckily, this bad code will break (at compile-time) when Foo changes the FooMap implementation.
      always use the C++ language to obtain best results
      Maybe in a code-obfuscation contest! =)
      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. =)

      Jon Katz :).... If you don't like to use the features, why not choose another langauge without them? (And with the nice feature of Garbage Collection!)

      Yes, C++ is hard to understand, and has lot's of "wierd-stuff" features, but they are all there for a reason, so I'm buggered if I gonna refrain from using them.

      --
      SLOGEN [ http://ungdomshus.nu : Sebastian cover music]
    21. 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.
    22. Re:Partial List by Anonymous Coward · · Score: 0
      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.
      std::string wasn't designed for the STL, but it's an independently developped class which became "STLified" after the fact. This explains a lot of the interface (which would probably fit much better had string been designed for STL)
      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.
      The line is very clearly drawn: Except for operator[], you only ever use integer indices in strings - for the reason I gave above.
  45. SGI-STL Port by JBMcB · · Score: 1

    Here's the portable SGI STL library, which is pretty good. Replace the crappy VC++ 6.0 version!

    http://www.stlport.org/download.html

    --
    My Other Computer Is A Data General Nova III.
  46. 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.

    1. Re:Bad inline optimisation. by Anonymous Coward · · Score: 0

      Not only that, but virtual functions aren't the end of the world, performance-wise. No, you don't want to use them for performance critical accessors or other teeny functions, but for most things they don't get in the way much.

    2. Re:Bad inline optimisation. by Anonymous Coward · · Score: 0

      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.

      I've never ran across a compiler that's as bad as gcc. Inline functions are a very good thing performance-wise, in this case it's the shitty compiler that's the problem not STL.

    3. Re:Bad inline optimisation. by Phil+Wilkins · · Score: 1

      Amen brother! About the only good thing you can say about GCC is that if you don't like it, you can at least attempt to fix it.

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

    2. Re:Enterprise issues with STL by 21mhz · · Score: 1

      Unfortunately, STL's use of templates and inlines can inflate the size of your code in exchange for raw speed.

      At times it's not even "in exchange", considering degraded locality of code for instruction caches.

      I read a few days back about generics, a proposed extension for Java that resembles C++ templates, but only to an extent. I'd say the extension is very elegant, if one accepts the idea of the single-rooted object hierarchy.

      --
      My exception safety is -fno-exceptions.
  48. Re:I never learned STD by Anonymous Coward · · Score: 0


    Uhhh. Do you know what you are talking about? The container classes in the STL blow the MFC container classes out of the water. I doubt that the engineers at Microsoft would even argue this point (I wonder what Herb would say). Furthermore, MFC simply does not have anything comprable to the STL algorithms. Nothing.


    You do realize that the STD, as you call it, is not a GUI library?

  49. Biggest problem is Thread Safety by bdrosen · · Score: 0

    Different implementations have different degrees of thread safety. Some implementation are very good with thread safeness, others don't do anything and most fall somewhere in betweeen.

    --
    Brett
  50. Bloody template errors! by ArchMagus · · Score: 1

    Template error reporting is, at least in MSVC, almost totally incomprehensible. It takes quite a long time to figure out what each error means (and it's not usually that easy to figure them out.) And, remember to put spaces between your >'s. If you don't, the compiler will mistake them for shift left and right, and the errors don't help.

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

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

    1. Re:STL documentation by Ryan+Amos · · Score: 1

      CPPReference.com is also a very nice ref site.

  53. STL Downsides? by bssea · · Score: 1, Informative

    To me the *concept* behind the STL is good. It's meant to be generic with little speed reduction. I just don't think the C++ STL is a good implementation.

    My Reasons:

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

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

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

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

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

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

    These are my problems with the STL. I have other problem with C++ in general but the STL can't be faulted for those (except the STL is in C++).

    The STL does have advantages but I don't think the advantages outweigh the disadvantages.

    --sea

    1. 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));
    2. 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"

    3. 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
    4. Re:STL Downsides? by Anonymous Coward · · Score: 0
      Remember, C++ is a young language with a young standard.

      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.

    5. Re:STL Downsides? by Anonymous Coward · · Score: 0

      YOU SHOULD NEVER INHERENT FROM AN STL CONTAINER. Period.

      vs.
      Suposing you want to create a string class with a subset of the functionality in std::string

      Umm, std:string is NOT an STL container. I don't think that string is even part of the STL (a subset of the C++ Standard Library). So, it still stands that you don't inherit from an STL container.

    6. 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
    7. Re:STL Downsides? by Anonymous Coward · · Score: 0

      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.

      I'll disagree with this one. And strongly to boot. Genericity at runtime is just too risky. Compile-time genericity, even as unperfect as in C++, has the tremendous advantage of catching most errors before execution. Discovering weird things at runtime is, in my opinion, a script feature :)

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

      True, but we get type safeness (not perfect but still nice) and get rid of those ugly and error-prone casts.

      the STL is *not* standardized, check your implementations.

      False, the interface to the STL is standardized.
      True, the implementation isn't but should never be anyway.

      I disagree. You want to extend an STL containter to create better ones.

      If you want to play on the safe side, I don't think you should ever consider inheritance. Virtual destructors anyone ?

      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.

      Wrong reason. I believe most did avoid the STL because those projects started quite some time ago (C++ is young) and mostly because of: 1. lack of free implementations respectful of the standard 2. to avoid compiler headaches My .02 euros :) Thomas.

    8. Re:STL Downsides? by sholden · · Score: 1
      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.


      You could privately inherit and provide wrappers for the subset, or just have a string object in your object and provide forwarding member functions.

      Publically inheriting *will* cause problems unless you and everyone who uses your new class are extremely careful, the following for example would be an error:

      string *s = get_a_derived_from_string_ptr();
      // ...
      delete s;

      Since it's not safe to use your object in a very common idiom of inherited type usage it's not safe to use inheritance.

      Also since none of the methods are virtual it's useless anyway since:

      string *s = get_a_derived_from_string_ptr();
      s->some_member_f unctions();

      will call the member function in std::string not in your class.

      So what is the point of inheritance?

      Plus inheritance can never be used to produce a 'subset' of the behaviour. That violates the substitutable principle that is the entire basis of object oriented inheritance.

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

    10. Re:STL Downsides? by j+h+woodyatt · · Score: 1

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

      Objective Caml is one language which does that. I know there are others, but I can't think of their names just now. Oberon, maybe? Ada? Bueller?

      --

      --
      jhw
    11. 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
    12. 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));
    13. 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"

    14. Re:STL Downsides? by HopeOS · · Score: 1

      To illustrate the above text with some actual code, here's a simple example which iterates a list and prints the result. Code is compiled with MSVC6. Very simple stuff.

      // FYI: typedef vector<string> STRINGS;
      STRINGS::iterator s;
      for (s=vectStr.begin(); s<vectStr.end(); ++s)
      printf("%s ",s->c_str());

      Compiles to a whopping 51 bytes. Explanation is below for non-assembly readers.

      31: STRINGS::iterator s;
      32: for (s=vectStr.begin(); s<vectStr.end(); ++s)
      004012BE 8B 74 24 28 mov esi,dword ptr [esp+28h]
      004012C2 8B 44 24 2C mov eax,dword ptr [esp+2Ch]
      004012C6 3B F0 cmp esi,eax
      004012C8 73 27 jae main+2F1h (004012f1)
      004012CA 83 C6 04 add esi,4
      33: printf("%s ",s->c_str());
      004012CD 8B 06 mov eax,dword ptr [esi]
      004012CF 3B C3 cmp eax,ebx
      004012D1 75 05 jne main+2D8h (004012d8)
      004012D3 A1 20 20 40 00 mov eax,[__imp_?_C@?1??_Nullstr@?$basic_string@DU?$cha r_traits@D@std@@V?$allocator@D@2@@std@
      004012D8 50 push eax
      004012D9 68 14 30 40 00 push offset string "%s " (00403014)
      004012DE FF D5 call ebp
      004012E0 8B 4C 24 34 mov ecx,dword ptr [esp+34h]
      004012E4 83 C6 10 add esi,10h
      004012E7 83 C4 08 add esp,8
      004012EA 8D 46 FC lea eax,[esi-4]
      004012ED 3B C1 cmp eax,ecx
      004012EF 72 DC jb main+2CDh (004012cd)

      And now the explanation...

      esi = vectStr.begin; // esi is the iterator
      eax = vectStr.end;
      if (esi == eax) goto done;
      esi += 4 bytes; // advance esi to string data

      next:
      eax = *esi; // dereference string data

      if (eax != NULL /*ebx === 0*/) goto print; // casual check for null (c_str() inlined)
      eax = "";

      print: push eax; // param 2 to printf
      push address of string "%s "; // param 1 to printf
      call printf; // ebp === printf

      ecx = vectStr.end; // stack is off by 8 here because of call to printf
      esi += 0x10; // step forward 16 bytes to get to next string data pointer
      esp += 8; // pop 8 bytes off stack (cleanup printf call)
      eax = esi - 4; // eax gets current position of string (esi points to string data, not the string itself)
      if (eax != ecx) goto next;

      done:

      Not exactly what I would call bloated code. Could you do it faster by hand? Of course, but why bother- it's just a vector of strings. Certainly you could find a better use for your time.

      -Hope

    15. Re:STL Downsides? by Anonymous Coward · · Score: 0

      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.

      Oh, for heaven's sake -- stop being so dramatic! It will work perfectly fine if the derived class doesn't use a destructor. And if someone is deriving a class from std::string, then chances are pretty good that they're just adding some simple extensions that don't require a special destructor.

      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.

      The fact is that deriving from STL classes can safely be done in some cases, and you need to learn EXACTLY what those cases are before you can start trying to pass yourself off as some kind of C++ expert on this issue.

    16. Re:STL Downsides? by Anonymous Coward · · Score: 0

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

      No, sir; in C++, as opposed to Java, Smalltalk, etc, generics are intended to be generated and resolved at compile time - the language's design wants to do as much at compile time as possible. See Stroustrup for the C++ design goals.

      RTTI was added to C++ to handle those kinds of programs that need runtime type checking, *not* because runtime checking was the generally preferred way to go. C++ perfers compile-type checking by design.

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

      If you want to be able to include two or more types of objects in a generic C++ container, then you have to either (a) make those two types subtypes of a base type, or (b) use a compile-time generic container like void* to hold references to the objects. Again, C++ as a tool was designed to prefer compile-time checking over runtime checking.

    17. Re:STL Downsides? by technoCon · · Score: 1

      I looked at the hawkstein/lkaos debate and believe two smart guys are looking at the same dataset through two different paradigms.

      Back in the C days, you could do major heap big juju with the preprocessor. It was hard to understand, but it was cool. Nowadays we have C++ and the bright boys who understand the language best are doing things in c-front that i used to do in the preprocessor.

      It is a completely different paradigm.

      Is the C++ a code generator that generates C++ code that, oh by the way, is in turn transformed into runtime opcodes? (i grokked this in chapter 2 & 3 of _Modern C++ Design_)

      I'll wager that lkaos is a really good programmer who doesn't use templates or typedef statements very much. And if he's old enough to precede C++, he probably viewed the preprocessor with suspicion. Probably with good reason.

      I think that when we say "generic programming" two different ideas are in play. i believe hawkstein thinks that generic programming means rely on mr. template author to come up with a generic way to express an algorithm so that once you supply particulars like int, float, & myclass, then mr. compiler will generate optimized code better implementing that algorithm than you could do by hand. (i'm not asserting that's true, i'm asserting that's the rationale.)

      my suggestion to lchaos is to spend a few hours with _Modern C++ Design_ by Andrei Alexandrescu and grok the alternate way of thinking about typedefs, templates, and generic programming. You may still think it is still evil, but you'll understand better how it IS evil. And if you don't, you'll see where hawkstein is coming from.

      btw, i love hawksteins' shy tenative way of hinting at what he thinks is best. &lt grin &gt i wish he wouldn't hold back so and tell us what he really thinks.

      smiles and cheers,

      steve poling
      grand rapids, MI

    18. Re:STL Downsides? by Anonymous Coward · · Score: 0

      YOU SHOULD NEVER INHERENT FROM AN STL CONTAINER. Period. There is no good reason to do this.

      Huh? Your other points were rational, but that one was just silly. I've inherited directly from STL classes extensively and have never had a problem with it. Of course, my extensions are usually pretty small, mainly to add a few missing features (like for example, loading a string from a Windows resource; or adding a special searching option to a vector or map). Works great!

      There's nothing special in the STL classes that makes them any riskier to use as base classes. In fact, they're probably LESS risky to derive from because they're pretty well designed. (You don't have to worry about them missing a copy ctor, or some other defect like that.)

    19. Re:STL Downsides? by epine · · Score: 1


      RTTI was intended for no such purpose. 99 times out of 100 the use of RTTI is a red flag for a serious design flaw.

      I've been using STL since nearly the day HP released the first reference implementation and I can't think of a single occasion where I've used RTTI except to break a compiler just for fun.

      You've completely confused the notions of genericity with polymorphism. generic programming is sometimes defined as static polymorphism: polymorphism which resolves ***at compile time***.

    20. Re:STL Downsides? by epine · · Score: 1


      You might think you are doing yourself a favor, but you aren't. The other response explains some of the reasons. There are more. Many many more.

      One of the areas where the C++ language could be improved is allowing classes to declare the formal requirements on any derivation from that class so that incorrect (unsafe) derivations were difficult to pull off.

      Just because something is a class, and C++ allows almost any class to be inherited, that doesn't mean you should go ahead and stick it in your ear.

      A more viable route to the same end is to write a template adaptor class. Unfortunately, you'll learn more from trying to do this than you are prepared to cope with.

      Short cut: the longest distance between two points.

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

    22. 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));
    23. Re:STL Downsides? by mvonballmo · · Score: 1

      As compared to what language???

      Take a look at Eiffel for a truly object-oriented implementation of generic containers. Eiffel's container library uses generic containers extensively in an intuitive hierarchy of classes representing many common containers.

    24. Re:STL Downsides? by Anonymous Coward · · Score: 0

      Are you sure you actually know anything about C++, or the STL. You kind of make yourself look like an idiot here by either a) suggesting stupid things, or b) not providing any examples to back up your claims.

    25. 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
    26. Re:STL Downsides? by Bytenik · · Score: 1

      As long as your subclass doesn't add any member data that requires destruction, the "delete s;" won't cause a problem (i.e., if the destructor for the base class and subclass are the same, then it doesn't matter which one gets called).

      Extending a string class in this way allows you to have access to the extended functionality where you need it. Furthermore, it allows you to pass instances of your new string subclass anywhere that a string instance is expected.

      Writing a class that simply "has a" string and provides wrapper methods won't let you do this.

      Of course, since there is a danger of this tool being used improperly, you should document your decision to help prevent others from wandering into a trap.

      --

      "Scientists prove we were never here."
      -- Devo

    27. Re:STL Downsides? by Anonymous Coward · · Score: 0

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

      Sorry, that doesn't cut it.

      The other programmer's mistakes are totally independent of whether you choose to derive a class from STL or not.

      The fact is that the STL is out there for everyone to use.

      You simply can't change how other programmers use the STL by applying coding discipline to your own code.

      I know exactly what you're trying to say and do here with your style rule. At an earlier point in my career, I had that same attitude too. I thought that if I applied strict discipline to myself, it would somehow "rub off" on the other developers. But experience has shown me that approach doesn't work to change other programmer's behaviors, for the reasons I presented above.

      You really do need to think through this completely. You've got a significant gap in your logic on this issue.

    28. Re:STL Downsides? by Anonymous Coward · · Score: 0
      "Generic stuff in runtime"

      Now wouldn't that be an interpreted language?

      Darn, it does seem stupid to bash on "generic stuff at compile time", now don't it?

    29. 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));
    30. Re:STL Downsides? by Anonymous Coward · · Score: 0

      You wrote:
      Also since none of the methods are virtual it's useless anyway since:

      string *s = get_a_derived_from_string_ptr();
      s->some_member_f unctions();

      will call the member function in std::string not in your class.

      So what is the point of inheritance?

      The point is to add functionality that wan't in the base class. There may be situations where polymorphism isn't needed. And in those cases, it makes perfect sense to add functionality by using derived classes.

      I would strongly recommend that you start learning how to use the OO paradigm both with and without polymorphism -- it will make you a much stronger programmer.

    31. Re:STL Downsides? by sholden · · Score: 1
      You wrote:

      Also since none of the methods are virtual it's useless anyway since:

      string *s = get_a_derived_from_string_ptr();
      s->some_member_f unctions();

      will call the member function in std::string not in your class.

      So what is the point of inheritance?

      The point is to add functionality that wan't in the base class. There may be situations where polymorphism isn't needed. And in those cases, it makes perfect sense to add functionality by using derived classes.

      C++ has private/protected inheritance which does this if you really don't like forwarding functions.

      Violating the substitutablility principle because it saves you forwarding some functions is just plain silly. Someone else is going to use your class which inherits from std::string, but is not actually subsititutable with a string as if it is, since by publically inheriting you have claimed it is.

      I would strongly recommend that you start learning how to use the OO paradigm both with and without polymorphism -- it will make you a much stronger programmer.

      I have, I must admit though I don't plan on violating substitutablility while my code claims it is substitutable just to save me some typing.
    32. Re:STL Downsides? by Anonymous Coward · · Score: 0

      > C++ has private/protected inheritance which does this if you really don't like forwarding functions.

      Violating the substitutability principle because it saves you forwarding some functions is just plain silly. Someone else is going to use your class which inherits from std::string, but is not actually subsititutable with a string as if it is, since by publically inheriting you have claimed it is

      You're assuming that the substitutability principle is being violated. But what if it isn't?

      It IS possible to derive a class that has non-polymorphic methods, but at the same time preserves the substitutablility principle.

      My original statement stands. Sometimes a new and useful method can be added to a derived class that does not require polymorphism to implement. And if this new (non-virtual) method does not violate the substitutablility principle, then it doesn't pose a risk.

  54. Re:FP! by Anonymous Coward · · Score: 0

    groten

  55. Debugging Problems by Ob+the+Rat · · Score: 1

    One problem that I've run into in MS Visual C++ is that the debugger has a different allowed symbol name length than the compiler (512 max for the debugger). The only time this was a problem was with some client code using embedded name spaces and templates containing STL templates (don't ask). The same code could be compiled and debugged under gcc/gdb, and the problem may have been fixed in more recent versions of MSVC++.

    As far as the STL itself goes, it can save you a lot of time and trouble, and is becomming available in more places all the time. I

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

    2. Re:Debugging Problems by Anonymous Coward · · Score: 0

      Put

      #pragma warning (disable: 4786)

      before including STL-headers

      --
      ah

  56. Re:I never learned STD... sorry for you by sesamo · · Score: 1

    MFC and ATL use STD.

    STD brings more than algorithms. They have a good consistency in concepts and paradigms.

  57. 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.
  58. 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 Stormalong · · Score: 1
      I ran into this same problem with our web caching software when I ported it to CE (iPaq). Fortunetly, a little web searching turned up a lifesaver: http://www.stlport.org/

      It compiles on many platforms.

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

    3. Re:Embedded Platform Issues by Anonymous Coward · · Score: 0

      Have you considered using STLB?

    4. Re:Embedded Platform Issues by Anonymous Coward · · Score: 0

      Winblows CE (should be FU) doesn't support a great deal of the ANSI C library (count the number of C functions that have "unsupported" next to them in the documentation. The fact that most of stdio is not implemented is appalling), so using ANSI affects your portability just because Windows sucks, huh?

    5. Re:Embedded Platform Issues by Anonymous Coward · · Score: 0

      In addition to the 3rd party libs others have mentioned, eVC 4 now supports STL.

      What's worse is the time I tried using STL Strings on a RIM 950. The standard "Hello World" application went from something like 50k to 800k. When you're limited to 4M of flash for the OS and apps, that's bloat!

    6. Re:Embedded Platform Issues by Anonymous Coward · · Score: 0

      > That's the stupidest thing I've heard all day.

      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? I've seen plenty of systems without enough storage to hold an stl library much less the library and all the application software.

    7. Re:Embedded Platform Issues by Anonymous Coward · · Score: 0

      VxWorks supports STL.... toss that CE stuff
      and run away from the dark side.

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

    10. Re:Embedded Platform Issues by kangasloth · · Score: 1

      STLport for one.

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

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

    13. Re:Embedded Platform Issues by Handyman · · Score: 1

      (Switching from std::string to CString to get something to run on a PDA.)

      You don't switch to something thats even LESS portable.

      I'd rather think they made a brilliant move. As their software now runs on a PDA, I would consider it more portable.

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

    15. Re:Embedded Platform Issues by Anonymous Coward · · Score: 0
      Using STL did not affect your portability because it had already been eliminated when you selected a Micro$oft environment.

      What the hell did you expect?

  59. 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.
    1. Re:this is wrong by Anonymous Coward · · Score: 0

      Well, you only get a vtable when you have virtual functions. As with anything, you have to know what you're doing. This is especially true with the STL and with virtual functions and other C++ stuff. I don't think you'd want vtable look-ups all over the place inside some critical loops or anything, but they shouldn't get in the way much depending on how you use it.

    2. Re:this is wrong by joshwalker · · Score: 1

      Of course, you have to understand any API you choose to use. The exception specifications for STL are well documented, so you know when an exception could potentially be thrown.

      vector.push_back() is about as fast as you could wish (0(1) time). If you try to insert into the middle of a vector, you will get a performance hit, however, since many elements have to be moved to make space for the new one. If you need insertions in the middle, you should be using list.

      STL is much more than data structures. The three tiers are Containers, Iterators, and Algorithms. Data structures (containers) are just one part.

  60. 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!
    1. Re:too much time by Anonymous Coward · · Score: 0

      we are victims ...
      trust us we know what you are talking about.
      Ive never seen a good opinion, like this one, about the STL stuff. We both working at a company for a STL Lover ... you hit the bulls eye

  61. 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 catf00d · · Score: 1

      Regular expressions are, in all likelihood, going to be included in the next version of the Standard Library. The standardization committee is meeting in Curacao discussing it right now. There are already excellent C++ libraries for doing regular expressions that integrate cleanly with STL. There is regex++ and GRETA, take your pick. I wrote GRETA, and it passes PCRE's regression test, FYI.

    5. 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.
    6. Re:Vendor specific by Zathrus · · Score: 1

      We were going to use regex++, but large portions of boost don't play happy with AIX. AIX really does have a lousy compiler/linker. We've been struggling for days now to get compile/link times down to something reasonable, and hopefully reduce code bloat too. Doesn't help that shared libraries are a major PITA on AIX either.

  62. 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 Anonymous Coward · · Score: 0

      Just because you tested it doesn't mean that you found all the bugs. Especially if it's ugly, obscure, hacked-up code.

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

    4. Re:heh... by kawika · · Score: 1


      >> really ugly Perl

      This should have been moderated as "Redundant"

      :-)

    5. Re:heh... by zaphod110676 · · Score: 1

      True it doesn't mean that you found all of the bugs. In fact I highly doubt that you will ever find all of the bugs on any piece of code that isn't trivial.

      Don't write code that is ugly, obscure, or especially hacked up. This is where planning comes into play once again. You need to have a clear understanding of what you are trying to implement or the use of STL and/or OOP is probably a bust.

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

      I love Perl. =)

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

      STL isn't, at least not with today's compilers, although you can approximate it for the *common* errors with a sed script.

      One word: typedefs.

      The code becomes much easier to read when you typedef the vector::iterator to something else instead of just trying to use all the 's.... unless you mean the compiler error messages (those can get nasty, especially with typedefs - you don't see in the code what the compiler is talking about!).

      MIKE

      --
      Beware the JabberOrk.
    8. Re:heh... by zaphod110676 · · Score: 1

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

      I'll buy this. You are right. The debugging process can never end if we are going to strive for improvement and if debugging is made harder due to poor implementation it's like someone throwing rocks down at you while you are climbing a cliff.

      --
      To Do: 1. Take over world 2. Pick up Milk and Bread on the way home
    9. 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...

  63. Try out the SOOP by ceswiedler · · Score: 0, Troll

    The "Standard Object Oriented Library" for C++. You'll find it here. (Warning, blatant goatse.cx link)

    What the hell are these specification designers thinking? Just throw everything in there? We make a language (an extension, anyway) with somewhat decently implemented classes and objects. Years later we remember we haven't written a library for it yet. At the same time some brightlight wants to add templates to the already horribly complex language, and so we create our standard library using this new feature and nothing else. The STL isn't just based on templates for rational things like containers, it uses templates for everything imaginable. Who needs a template parameter for an allocator function? Who needs strings to be such a generalized class that I can use them to handle an array of kitchen sinks, and provide automatic Dran-O too? The "joy" of templates drove every other thought out of their heads when they came up with this crap.

    Programmers code in different ways. Not everyone wants to use templates; they're by far the most debated "feature" of C++. Why the hell did Stroustroup et al decide to ram them down our throat? When I program in C++, I use standard C libraries or roll my own object-oriented ones.

    Just wait till next year, when they add threading support based on functional programming and graphics code which uses an AI core to figure out what you want to draw before you know it yourself.

  64. 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 Anonymous Coward · · Score: 0

      Smalltalk? Fortran? Surely you jest.

      FORTRAN is very much alive thank you...if you're talking FORTRAN-77 then yes, it is very much in the dustbin of history. Not so the latest variants.

      Smalltalk is VERY much alive and thriving, thanks so much. Check out Squeak, Smalltalk/X, or IBM's Visual Age. Squeak in particular is doing very exciting stuff with interfaces (Morphic) which is light years and a lifetime beyond C-style "toolkit" programming. The only Smalltalk that is DOA is GNU Smalltalk.

      And much to everyone's chagrin, COBOL is like the yellow cat that kept coming back...it won't go away anytime before 3001.

      Java (hype) and C# (hype++) may have the billboards, but they certainly are NOT "where everyone is going". I suggest you check out Python and Ruby before you spout that nonsense again.

    3. 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/
    4. Re:Probably slightly better than Fortran... by thammoud · · Score: 0

      >>Java is not a good laguage for building large enterprise level systems.

      EJBs, XA Transactions, Messaging, JDBC, XML, JSP, JNDI and JMX. Hmmm, what are you smoking ? Name one C++ standard equivalent. Just one and you win.

      >>C++ jobs pay much better than Java jobs (and Unix pays better than windoze).

      Learn the above and you will make a lot more money than C++.

    5. Re:Probably slightly better than Fortran... by epine · · Score: 1


      ]] The point is that ten years ago C++ was hyped to the same extent ...

      error: inference via hype; hype is nilpotent

      To dredge up a really old term: garbage in, garbage out.

      Ten years ago OO langauges in general were strongly hyped. The generic side of C++ evolved out of a growing recognition that there was another component of programming orthogonal to OOP. Many people regard the last ten years of C++'s evolution as the most compelling part.

      Any point which takes as its premise what the marketrons were saying is no point at all.

  65. 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 jungd · · Score: 1

      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.

      The dangling pointer problem is hardly anything to do with STL. You should be careful with pointers always. Also the STL DOES include a smart pointer template class - called auto_ptr. Of course a reference counted version like boost.org's shared_ptr would have been nice. I believe adding garbage collection to C++ and/or STL is being considered (a far superior option to using referenced counted pointers without language support IMHO).

      --
      /..sig file not found - permission denied.
    2. 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.

    3. Re:Advice from an STL battle-scarred veteran by stripes · · Score: 1
      good c++ and stl implemtation

      g++ 3.something and the STL that comes with it is not bad. Not stellar, but not bad.

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

  67. Rouge Wave??? by MrBandersnatch · · Score: 1

    Im obviously missing something here.How is he switching from "rouge wave" to the STL exactly? Serious question - what product do they produce?

    I *think* I've been using the ROGUE wave STL for years - it was purchased by Borland and incorporated into C++ Builder. If you want a good implimentation of the STL thats the product I'd recommend. VC6 STL support stank to high heaven if I recall correctly and I'm not sure how it fairs in the latest version.

    Speed isnt an issue with Builder, code bloat could be but there are ways to minimise the impact and the documentaion in relation to the STL is *excellent*.

    1. Re:Rouge Wave??? by BitHerder · · Score: 1

      Probably means he's switching to a different implementation of the STL - most likely whatever came with his compiler. Shouldn't be any code change, just a matter of including the right library.

      We used RW for a few years, now we just use the library included w/ MSVC. IIRC, RW had a number of memory leak problems (BoundsChecker went nuts on string). I don't know if these have been cleaned up in recent releases.

    2. Re:Rouge Wave??? by techentin · · Score: 1

      Rogue Wave changed its licensing scheme a year or so back. It used to be that you could buy a developer license for a few kilobucks and you were all set. But they changed their revenue model to include a per-deployment fee. That's right. Every person running your software has to pony up for a run-time license. Some folks can just add a few bucks to the sale price. Others have to look for an alternative to Rogue Wave.

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

  69. The only real downside is the implementations by mbrix · · Score: 1

    To sum up the different comments - the only real downside is the implementations on the different platforms. First of all, not all compilers have STL implemented fully (I think g++ 3.1pre has it all). Second, older systems and embedded systems totally lack an STL implementation. The rumours about the STL having a lot of overhead because of virtual functions etc. is not true - one of the goals with the STL was speed and therefor it was implemented without virtual functions, but just concrete templated classes. Sure, a std::vector has overhead compared to a built-in array, but development is usually faster using vector because it dynamically resizes and it throws exceptions when trying to reach an element which is out of range.

    1. Re:The only real downside is the implementations by Anonymous Coward · · Score: 0

      Actually STL does not throw an exception when reaching an element that is out of range. That would mean that each element access requires an index/size comparison, and if you look at SGI's code for example, there is no check; it just returns a value from an internal array, so you can still overrun your boundaries

    2. Re:The only real downside is the implementations by mbrix · · Score: 1

      You are wrong. Look at std::vector, it has both a [] operator and a at() member - the at() member throws an exception while [] does not, you have a choice.

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

  71. Binary incompatibility and buggy implementations by Brian+Quinlan · · Score: 1

    One of the problems with using templates in interfaces is that STL implementations may not be binary compatible between releases. Imagine the following libary interface:

    mylib.h
    -------
    vector<blah> getBlahs(void);

    The vector<blah> implementation is compiled into both mylib and the application that uses it (mayapp). The nasty part is that if mylib and myapp are compiled with different STL versions, then they may not be binary compatible. I encountered this problem when moving to gcc 3.0. It was amazingly difficult to debug the problem.

    Also, the gcc and VC6.0 STL implementations suck and have subtle incompatibilities.

    So, after being bitten hard a few times, I try to avoid STL like the plague.

  72. 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 Chris+Carollo · · Score: 1

      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.

      On the contrary, bounds checking is a necessary part of any solid app. Yes, it incurs a performance penalty, but that's what Debug builds are for! You obviously disable it in Release builds, but it's invaluable for catching over/underruns during development.

      I suppose you're against Assertions as well?

    7. Re:mostly downsides by emarkp · · Score: 1
      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 [horstmann.com]; it is unacceptable that this isn't part of the standard and isn't used by default).
      Read The Design and Evolution of C++. You'll find that one of the major principles in C++ is that you shouldn't pay for any feature you don't use. Breaking that rule requires that the feature (1) adds value to all or nearly all C++ developers, and (2) it can't be done any other way. Hence we have (for example) virtual functions, but if you don't want to use them, you don't have to. The STL containers were designed the same way: hence std::vector has operator[] which has unchecked access, but also has at() which does do range checking.

      Also, iterators are intended to represent meta-pointers. Should all pointer operations be checked? Say goodbye to performance.

      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.
      Profile, profile, profile.
      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.
      This is just plain wrong. I can simply use std::vector instead of arrays, and I don't ever have to worry about delete. Have you ever seen code like this?
      char* buffer = new char[n];
      //...
      delete [] buffer;
      Replace it with:
      std::vector<char> bufmem(n);
      char* buffer = &(bufmem.front());
      //...
      Say goodbye to delete for dynamic arrays.
      STL's complex semantics also make thread safety hard to guarantee.
      That is a very legitimate issue. And one that I have little experience with.
    8. 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.

    9. Re:mostly downsides by that_guy · · Score: 1

      Most of the time, boundschecking notices programatical errors, ie bugs. We wrote a wrapper class for vector and similar that just does an assert then calls the inherited method. This completely compiles out and helps tremendously when debugging.

      --

      Driving backwards on the highway of life
    10. 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));
    11. Re:mostly downsides by loudici · · Score: 1

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

      This is all relative. You do want some safety checks but i am glad that planes do not have to carry all the measuring equipment that is hooked
      onto reactors in testing labs. This is why i do not like java.

      --
      Dev elpizw tipota, dev phoboumai tipota eimai lephteros http://euclidian.org
    12. 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.

    13. Re:mostly downsides by emarkp · · Score: 1

      I'm aware of the boost libraries--scoped array is nothing more than a simple array which destroys itself. I often have to change the size of the arrays I allocate, making vector a better choice. You're right though that if my trivial example is all I need, then scoped_array would do the trick.

      Of course it's not in the standard.... :)

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

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

    17. Re:mostly downsides by epine · · Score: 1


      I see no reason why the C++ standard should impose policies, such as error checking, on STL library developers, who have an extremely wide range of interests to serve.

      If you want default error checking, obtain an STL implementation that performs default error checking. You don't understand my problems. I don't want your defaults.

      My understanding of the history of the STL is that many of the committee members who voted in favor of the STL were extremely impressed by what the generic approach promised.

      I agree that the STL containers are not particularly well suited as interface arguments. I find that I rarely do this. Either I create a template algorithm that takes generic iterators, or I pass application class objects directly.

      What you have failed to understand is that C++ was designed to serve many different masters. Much of the shape of the STL was chosen to make it possible to build efficient 3rd party libraries on top of the STL algorithms.

      These libraries might very well be performing their own error checking at a higher semantic layer. Layers upon layers of error checking finally lead to a completely safe library than no one can afford to use in a production system.

    18. Re:mostly downsides by epine · · Score: 1


      This is so much bullpucky.

      The vast majority of the STL algorithms have a natural, efficient expression. I've read as least three different STL algorithm library sources and I didn't find much exceptional in how any of them implemented the basic algorithms.

      The most complicated algorithms I can think of right now are the various sorting algorithms. The original HP implementation did a pretty reasonable job in making good use of the heap primitive. In order to implement these algorithms badly you'd need to completely ignore the model implementations.

      The containers and the string class are a different matter. I can imagine slow implementations of map and string. In the case of string, it's almost impossible to implement it to be efficient for all cases. But don't blame the algorithms. They are at least as reliable as qsort() or rand() from the C library.

      Once upon a time I had a version of Watcom which failed to implement the tail recursion properly and consumed linear stack space. It was widely documented that this is a required practice, but the Watcom programmer didn't bother to consult any precedents. If anything, these problems are less likely to occur in quality STL implementations.

    19. Re:mostly downsides by epine · · Score: 1


      If you make solid use of assertions, bounds checking internal to your container classes is completely redundant.

      Your own assertions provide diagnostics ten times more likely to immediately point to the precise location of the problem.

      Bounds checking is what you do after your engineering efforts have failed.

    20. Re:mostly downsides by epine · · Score: 1


      In the simplest examples, the cost of automatic bounds checking is not terribly onerous. It's somewhat more painful on architectures with small register files (e.g. x86).

      The problems with automatic bounds checking snowball when you write template code that expands through many layers. There are reasons why compilers can't always eliminate operations at the bottom of these compositions.

      What you end up destroying is compositionality. Rather than mandate checks at the lowest layer of the composition, it's much better for highly abstract code to enforce the correct preconditions at the top of the abstraction tower.

      If bounds checking has the end result of making good abstractions less viable, we can do without the bounds checking altogether.

    21. Re:mostly downsides by epine · · Score: 1


      I have to repeat myself here.

      Bounds checking is what you do once your high level engineering efforts have failed.

      If catching bound exceptions is commonplace on your projects, either your programmers are poorly trained, or your design lacks sufficient abstraction.

      I've worked on some very complicated C++ systems where bounds errors were at the bottom of the risk chart.

      Vastly more serious and difficult problems are managing allocation lifetimes, thread safety, and exception safety.

      Give up on automatic bounds checking. Throw me something that will solve a problem I don't already have under complete control to begin with.

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

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

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

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

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

    28. 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.
  73. 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 Anonymous Coward · · Score: 0
      To sum it up, C++ with the STL is the only language that meshes (not always prettily) performance computing with high level concepts.

      Only? Them's mighty strong words, bubba!

      You might want to check out Common Lisp. See these links before you make a fool of yourself.

      You could also qualify the statement to be something like: `` ... only buzzword-compliant language ... ''

      p.s. Notice that I've accepted the proposition that c++ is a high-level language. I probably should have pointed out that that's a questionable assertion. Roll-your-own garbage collection is not high-level!

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

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

    5. Re:It is hard to learn well by epine · · Score: 1


      Lisp blows C++ away in high level concepts?

      Like what?

      The type inference mechanisms in C++ have the full expressive power of a functional language. Type inference in C++ _is_ a functional language (type results are never changed once they are created).

      The problem with C++ is not lack of expressive power, but that the expressive power is often difficult to leverage out in its purest form.

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

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

  76. 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 joshwalker · · Score: 1
      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...

      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.

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

    3. Re:It's a "nonstandard standard..." by epine · · Score: 1


      A polynomial time map implementation does not conform to the STL standard which makes execution order guarantees.

      You presented your issue badly. You should have complained about a violation of the STL execution order requirements until they sent you something non-polynomial.

      Chances are they would have solved the problem by improving their algorithm rather than making the insertion of the first element a ten second operation.

  77. 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.
  78. 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
  79. 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
  80. What's the worst thing about the STL? by dagbrown · · Score: 1

    The error messages from the compiler whenever anything goes wrong.

    You know the ones I'm talking about, where the compiler unravels all of the levels of templates, leaving you with an error message that's about 20K long, most of it angle brackets.

  81. STL/C++ -- My experience... by pixel_bc · · Score: 1

    They're wonderful tools -- but mind you, like any other tool -- they can cause you great problems when used incorrectly. Watch your portability, and keep your code easily understood. Don't use every odd feature just for the sake of using it. Just be smart in your usage of the STL. I personally use them both in large scale projects, and think they're wonderful.

    Bear in mind, you're likely to see lots of negative press in this slashdot story. Remember -- The STL's and C++'s biggest detractors tend to be those who don't understand them.

  82. The STL is fast but in some cases not fast enough by twfry · · Score: 1
    Yes the STL has fast implementations of vectors, maps, etc. however it isn't as fast as you'd think. In my opinion the STL just isn't slow.

    An alternative is the LEDA
    suite of tools. Not only is it a faster implementation of the STL but many useful graph functions are built in. I know its not free, but they give out free licenses to students and anyone working in a research environment.

  83. 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 IkeTo · · Score: 1

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

      I still don't know what you are blowing...

      #include
      #include

      int main() {
      vector test;
      for (int i = 0; i 10; ++i)
      test.push_back(i);
      test.erase(test.begin()+5);
      test.erase(find(test.begin(), test.end(), 7));
      for (int i = 0; i test.size(); ++i)
      cout << test[i] << endl;
      }

    3. 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.
  84. Standard Compliance and STL ... by hazzzard · · Score: 1

    A number of postings have complained about the fact that many compilers / platforms / libaries do not follow the STL standard precisely. If that is one of your concerns, I suggest using Dinkumware's standard libary. This is the only implementation of the C++ libraries that is truely 100% specification conformant and well documented. I am not affiliated with this company in any way, but their stuff is kick-ass. So if you need something that works across platforms etc., go with them. As far as I remeber, Intel's C++ compiler also supports the dinkumware libararies, and is very ISO C++ compliant. If you use these two together, then you may end up with 100% ISO C++ / STL compatibility / support. Porting applications from one compiler to another or from one library flavor to another can be a bit painful. I would suggest you pay the price of kick-ass commercial implementations and start with them right from the beginning, if you care about these issues.

    1. Re:Standard Compliance and STL ... by BitHerder · · Score: 1

      Looks like MSVC++ 6.0 uses Dinkumware, also. P.J. Plauger's name is on all the files.

  85. Downside: no jeweler's "Rogue" by Anonymous Coward · · Score: 0

    The downside is, craybob, that "STL" is spelled just the way it sounds, and therefore you can't have the same kind of fun you can have in spelling "Rogue Wave" the same way you spell the name of that red stuff used in cosmetics and lapidary.

    (This is, like, the third time in a few days I've seen "rogue" spelled "rouge". Is it something in the water?)

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

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

    There are a handful of utilities that are designed to "translate" these types of error messages, and produce something human-readable (or at least developer-readable.)

    I suspect that compiler writers will eventually start using these same sort of techniques to present usable error messages for STL constructs. Hmm... might actually be interesting to do this for GCC.

    --
    "Great men are not always wise: neither do the aged understand judgement." Job 32:9
  88. It's still C++ by ndogg · · Score: 1

    C++ already, innately, carries with it a certain number of performance hits.

    And not all compilers handle templates in the same manner, or even correctly. By their very nature, templates create a lot of bloat. There are, however, tricks to keep that bloat to a minimum though.

    As already mentioned by many others here, STL is NOT a standard, but nonetheless, the currently best "implementation" is STLport. They actually strive for complete portability, unlike most implementations. They also strive to make sure it works with other programming features such as multi-threading.

    --
    // file: mice.h
    #include "frickin_lasers.h"
  89. vector - vector<bool> by lkaos · · Score: 3, Funny

    Stupid HTML

    --
    int func(int a);
    func((b += 3, b));
  90. DUMP RW by exodus2 · · Score: 1

    You should dump rogue wave. My company has been using tools, threads and thir stl. They have changes their licenceing so that rather than paying about 5k we now pay 50k because we distribute the binaries to customers. We are looking to dump them infavor of standard ms stuff because it will save us a ton.

    --
    .sigs suck, thus nothing here.
  91. 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.

  92. 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)
    1. Re:Not necessarily by cakoose · · Score: 1
      And if the forwarding is well-written, most/all of it can be inlined and otherwise optimized away. Voila -- 15 containers, all sharing code.

      But the process of inlining will generate a new copy of the generic code for every data type. If inlining is not done, you don't get the speedups associated with using templates over void* data types.

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

  94. Re:I never learned STD by Anonymous Coward · · Score: 0

    Trust a slashdot geek not to know. It would just be theoretical knowledge, anyway.

  95. 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.
  96. Need a strong application language? by defile · · Score: 1, Offtopic

    Try Python

    It's way easy to learn and understand and extremely powerful. Integrates well with C/C++.

    1. Re:Need a strong application language? by bytes256 · · Score: 0

      How is Python an alternative to the STL?

      --

      Slashdot, the site where everything's made up and the points don't matter
  97. 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 madmaxx · · Score: 1

      We've used STLPort on all our currently 'supported' platforms for a few years now (Tru64, Win32, Solaris, Linux) - and we can generally build with it or the vendor provided one. I agree that the Dinkumware STL that ships with VC6 is useless - avoid it if you can!

      --
      mx
    2. 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?

    3. Re:Experience with STL on multiplatform by David+Greene · · Score: 1
      EXTREMELY verbose compile error statements

      You can't blame the STL for that. That's a compiler (possibly language) problem.

      Memory High-water-marks: Some things don't really free the memory you want them to free, just hold onto it for next time.

      That's what custom allocators are for. In my experience the default works well most of the time. But you're right that some nasty pathological cases can crop up.

      --

    4. Re:Experience with STL on multiplatform by abdulla · · Score: 1

      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 isn't that more a c++ standards thing, there's a way to change this from being const in g++, simple compiler switch

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

    6. Re:Experience with STL on multiplatform by Tiger · · Score: 1

      You misunderstand me - we do strive for const correct programming. My point is, it's pretty difficult sometimes to sift through 6, 10, 14 lines of template name expansion just to discover that you're trying to cast a const iter to a non-const iter. At least it was at first, until you knew what it looked like.

    7. Re:Experience with STL on multiplatform by Tiger · · Score: 1

      We.. uh.. don't.

      I might be wrong, I haven't dealt with that issue directly. The problem had to do with initial loading of data (we deal with as many gigabytes of 3D flow data as the OS, FS, and available resources will let us..) where a couple of very large maps get used and then discarded.

      I *think* it's been alleviated by re-engineering that section such that smaller steps are used, so the high-water mark isn't as big.

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

    9. Re:Experience with STL on multiplatform by LordBrutish · · Score: 1

      We also use STLport on all platforms. Its debugging implementations answer one of the complaints I've seen on this topic -- difficulty debugging.

      For the other one (cryptic error messages), I cannot recommend STLFilt enough. This is a Perl script that intercepts the output from cl.exe (in visual studio . . . not sure why no one has adapted this to gcc yet) that reduces the complexity of STL error messages to a manageable level.

  98. Debuggers by Anonymous Coward · · Score: 0

    Everyone thinks template compilation errors are tough to look at. True, but looking at STL contents with a debugger makes me want to punch a cat.

  99. My main quip... by PhilJackson · · Score: 1

    My main quip about the STL is how hard it is to debug. Its difficult code to follow. The second quip I have isn't that big really: I always have to have a reference book handy becuse the header files may aswell be encripted! Otherwise I love it! :)

  100. complexity by ajrs · · Score: 1

    The real problem with the stl, (and C++ in general), is that the knowledge required to use templates is on the same order as the amount of knowledge required to make good use of classes, the C++ library, and the core 'C like' language.


    Understanding, and making good us of, all of the C++ feature is significantly higher than C.


    core language + library + platform => C


    core language + library + objects + templates + stl + platform => C++


  101. Downside of using STL by DuckDuckBOOM! · · Score: 1
    (not necessarily as oppposed to RW; I've no experience with it.)

    1: Build times and object sizes can go up. Way up. Often to unacceptable levels when using compilers that aren't adroit with templates, a la early HP-UX aC++.
    2: Many STL classes are difficult to derive from.
    3: Syntax can become convoluted when using complex structures, e.g. nested maps.
    4: STL containers tend to do a lot of small memory allocations, with concomitant potential performance and fragmentation issues. (Mitigating factor: you can plug in your own allocation code.)
    5: There are no virtualized containers (in the Standard, anyway,) which can lead to a lot of memory being expended on data which might be better held in a temp file.

    With the exception of [1] these are relatively minor concerns; I use STL daily, and wouldn't willingly do without.

    ddb

    --
    Life is like surrealism: if you have to have it explained to you, you can't afford it.
    1. Re:Downside of using STL by epine · · Score: 1


      1. unacceptable build times and object sizes

      The extra burden on the compiler is there for the benefit of the programmer.

      Compilers usually lag behind trends in how typical applications are written. It's much easier to improve a compiler when you have a representative code base against which to vet your changes.

      All of the problems I'm aware of have good solutions in principle.

      2. difficult to derive from STL classes

      The STL classes weren't designed to support derivation. The STL is designed so that you can write your own container classes (or class hierarchies) in such a way that they remain compatible with the STL algorithms. The algorithms are the design center of the STL.

      In other words, don't do this!

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

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

  104. 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.
    1. Re:STL strengths and weaknesses by David+Greene · · Score: 1
      Among the STL's (and C++ standard library's) deficiencies are...smart pointers (the only type included, auto_ptr, is not very useful)

      Why does everyone knock auto_ptr? No, it's not a generalized smart pointer and it was never intended to be so. But it has some very important uses and serves as good documentation of those uses. Read Herb Sutter's Exceptional C++ for some excellent examples.

      --

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

  106. 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?
  107. Re:Downside: no jeweler's "Rogue" by MrBandersnatch · · Score: 1

    I see "Rouge Squadron" is due out this week on the Gamecube in the UK also.

    For once I cant just say its thick Americans bastardising their mother tongue *sigh*.

  108. There are 3rd party STL implementations for CE by Erv+Walter · · Score: 1

    For example:

    http://www.dinkumware.com/libdace.html

    It's pretty decent although it can get expensive if you need to license it for a large development team.

    --
    -- Erv Walter
  109. steep learning curve by Mr.+Asdf · · Score: 1

    The most common complaint I hear is that it is too complex and takes too long to learn. I would agree with that if you are only trying to write a simple application, but in that case you could probably get away with just learning vector and string. Who said good has to be associated with easy to learn? (Maybe vim is a good example of this....)

  110. 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 Anonymous Coward · · Score: 0

      The reason generic programming is so desasterously ugly is that c++ was not designed to have this feature, it is an accident. it is quite straightforward to design a language with nice generic programming facilities, in particular typechecking and basic datatypes such as lists. see http://cs-www.cs.yale.edu/homes/taha/MetaOCaml/ for an example of how to do it right

    2. Re:Debugging is the downside by macrom · · Score: 1

      Well, I think meta-programming came around by accident. Yes, you can do some cool things with templates, but were C++ templates really designed with meta-programming in mind? Please correct me if I'm wrong, but I don't think Bjarne was sitting in his office thinking that he could facilitate generic programming while allowing programmers to compute cosine angles at compile time with the same type of code. Meta-programming happens (there's a new .sig for someone), but only because the language has a "loophole" (for lack of a better term) that allows you to write that type of obnoxious code.

      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.

    3. 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.
    4. Re:Debugging is the downside by McGregorMortis · · Score: 1

      I love the STL like a brother, but you're right about the shortcomings of "template meta-programming". There is a language that has the sort of compile-time coding you suggest: Waterloo Port. Among it's many unique features was that variable definitions were written as a block of code that executed in the compiler. You could, for example, define an array of "unsigned[32]" that was initialized by a "for" loop with values from 1 to 100. All done at compile-time. Sadly, Waterloo Microsystems is long-dead, and with the collapse of Hayes, all traces of the language and operating system I loved are gone :-(

    5. Re:Debugging is the downside by Heinrich · · Score: 1
      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.

      Do you have considered Eiffel or Ada? Both come with generic programmic and with a far more friendly syntax. However, they require you to specify type constraints. This adds security, it makes clear what the requirements of a type you want to pass as template argument are. But it is also more restrictive than C++.

      In general, most oddities of C++ including its syntax are simply due to the heritage of C. And if a large framework is given, there are not so many options left to add something like templates. As in the case for member functions, you have to repeat the whole prefix over and over again because there is no construct that encloses the members outside the class declaration. They can be even spread over as many source files as you like. And <...> most likely was introduced for template parameters instead of (...) to avoid ambiguities. The result seems to be a fair deal. After all, the use of a template does not look that bad. Just the templates themselves look like a mess.

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

    7. Re:Debugging is the downside by xphase · · Score: 1
      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.

      You find that with most libraries. On most large projects one usese the debugger constantly, to find out why the code isn't working "right". So I don't really find digging through the debugger a chore since you then really know what your code is doing.

      But when it does compile and run correctly STL is pretty nice!

      Agreed.

      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.

      People may not like me for this answer, but how about Ada? I've not had any problems with their generics(Similar to templates) on the client side(I'm not writing the generics).

      For example:
      type Light_Spectrum is range 10 .. 900;
      package Wavelength_IO is new Ada.Text_IO.Integer_IO(Light_Spectrum);

      Defines a new type(Wavelength) which accepts the integers from 10 to 900(inclusive), then instantiates an IO package for it. This allows for basic input and output of the type Wavelength.
      NOTE: Wavelength is not an integer, it's stored however the compiler wants to store it.

      Here's part of the declaration of Ada.Text_IO.Integer_IO.

      generic
      type Num is range <>;
      package Integer_Io is
      Default_Width : Field := Num'Width;
      This says that type Num is some range that we don't know yet, that's it, then just use Num where ever you would use the Actual type.

      I like it, but I'm really tired so this might be garbled somewhat.

      --
      The following sentence is TRUE. The previous sentence is FALSE.
    8. Re:Debugging is the downside by Anonymous Coward · · Score: 0

      i can think of two languages. python and smalleiffel.

    9. Re:Debugging is the downside by Anonymous Coward · · Score: 0
      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.

      Ever work with LISP macros?

    10. Re:Debugging is the downside by Anonymous Coward · · Score: 0

      Eiffel supports generic programming without the syntactic horrors of C++ (IMHO).

    11. Re:Debugging is the downside by Anonymous Coward · · Score: 0



      Try Objective Caml (ocaml) if you want to avoid the syntax of C++ templates, and have generic programming. There are of course drawbacks to this choice, but this is offtopic.

    12. Re:Debugging is the downside by Anonymous Coward · · Score: 0

      The obligatory Forth reference.

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

    14. Re:Debugging is the downside by descubes · · Score: 1

      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.

      It's possible. The language is called LX.

      --
      -- Did you try Tao3D? http://tao3d.sourceforge.net
    15. Re:Debugging is the downside by Lucas+Membrane · · Score: 1
      Four years ago, the difficulties of debugging STL under gcc (djgpp) was one major factor that killed a project I was on. Maybe it's better now.

      The ugliness of the generated code is also a minus. You can write C++ like a COBOL programmer, as I do, eg, useLongTypeNamesLikeThisOne. When you try to use an iterator for an STL collection of those buggers, you've got 3/4 of a lethal dose of ugly.

      Overall, I recommend STL strongly without reservations -- it stringently abates the lines of code -- but it's gotta work or you're hurting. Find someone who has successfully done something like what you want to do and copy their style with it.

    16. Re:Debugging is the downside by Samarian+Hillbilly · · Score: 1

      I couldn't agree more. I've checked out a few C++ "meta-compilers", but they're nothing like having the facilities built in. The essence of the problem is to have a language that cleary distinguishes static from dynamic decision making. I find that this distinction takes up an enourmous amount of my design time on any given project and it should be reflected in the tools available in the language.

    17. Re:Debugging is the downside by Matthew+Austern · · Score: 1
      Do you have considered Eiffel or Ada? Both come with generic programmic and with a far more friendly syntax. However, they require you to specify type constraints. This adds security, it makes clear what the requirements of a type you want to pass as template argument are. But it is also more restrictive than C++.

      I can't speak to Ada 95, becuase I've never done any serious work in it. (I do know that Alex Stepanov and Dave Musser wrote a precursor to the STL in Ada 83, and they thought that Ada 83 was insufficiently expressive for the kind of library they were trying to write. Perhaps Ada 95 has removed some of Ada 83's limitations.)

      I have tried using Eiffel. I think it's an interesting language, and it deserves to be better known than it is. It does some things (like design by contract) better than any other language that I know of. It's a well worked out system based on a consistent philosophy, and that's almost guaranteed to be interesting regardless of the a priori merits of the philosophy.

      However, I have found Eiffel's generics to be frustratingly limited compared to C++'s templates. One problem is that Eiffel demands that genericity be constrained (Eiffel's "unconstrained genericity" is just a special case of constrained genericity: it uses ANY as the constraint class), and the only kind of constraint it understands is constraint by inheritance. I agree that constraints are very important, but I find inheritance to be a relatively uninteresting special case. Constraint by inheritance misses many of the important kinds of constraints, and it behaves poorly when you're dealing with a constraint that involves several different type parameters.

      I believe it's possible to have a language that's better for generic programming than C++ is. I don't think that Eiffel is that language. (And the generic extensions to Java are even less so.)

    18. Re:Debugging is the downside by KatieL · · Score: 1

      "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." To solve this I save off compiler error messages and pass them through a filter (in perl) that knocks out all the stuff between pairs to certain levels. And definitely replaces "basic_string" with "string". Other compilers (not GCC) are worse - they don't provide enough detail. C++ Builder has a habit of just reply "No. Wont." and not explaining why.

    19. Re:Debugging is the downside by KatieL · · Score: 1

      This should be "basic_string" with "string".

      Damnit, this site can remember who I am, it can remember my comment reading settings, why the hell can't it remember whether I normally post in HTML or text?

    20. Re:Debugging is the downside by KatieL · · Score: 1

      Hmm it's not going to put those angle brackets in there is it?

      "basic_string OPEN_ANGLE DOT STAR CLOSE_ANGLE"...

    21. Re:Debugging is the downside by Anonymous Coward · · Score: 0

      It seems that what you are describing is related to Aspect Oriented Programming (AOP), which is a potentially emerging new programming paradigm.

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

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

  112. Going from RogueWave Tools.h++ too!! by Anonymous Coward · · Score: 0

    It's cool that we are not the only one leaving Tools.h++. RogueWave did some relly not very nice licencing changes. they though that they had us by the balls and just made a huuuuge adjustment to the license terms. That made us drop Tools.h++ the same day. STLPort is much better!!! Pitty we did not try it to begin with...

  113. C++ library by Anonymous Coward · · Score: 0

    I intended to write a smaller essay on this matter, until I realized the one asking the question still thinks of it as STL.

    The fact is that since the ISO/ANSI C++ standard was ratified in 1998 there is no "STL". A "C++ implementation" is required to supply, among other things, what used to be known as STL.

    As such, the question "so what are the downsides to the STL?" could be summarised:
    It's an international standard, and Microsoft can't buy it and destroy it (or as they say, "embrace and extend" and extuinguish).

    The downsides are that you write portable code (this is a _real_ downside if you're a Microsoftie since it's the opposite of the corporate policy of "lock-in" and "vendor dependence").

    I think your question is malformed. It should have been "What can we gain by using standard C++".

  114. Bloat, etc by buserror · · Score: 1

    There is no compiler available that can optimize away the bloat the stl generates. Code bloat might not be a problem memory wise, but it'll have an impact on your instruction cache anyway.

    Debugging usualy involves rewritting the bit of code without the STL so you can actualy understand the execution path.

    If you, by mistake, fall into the STL itself with a debugger, you usualy stay there for the next 10 minutes trying to step out of it.

    Usualy teaches non-experienced programmers to write stupid code, like passing objects via value instead of references "because the compiler will optimize it away" Or making a vector for 5 bytes "so I can't go out of bounds because the operator [] checks it for me". Or using hash tables for 10 values maximum "because hashes are fast!", etc etc. makes for lazy bastards you'll have to Zap +4. Oh and they swear recursion is cool, too. Stack space is infinite after all.

    char *data;
    memcpy(data, someotherdata, somesize);
    "Why it crashes, my data is declared!"

    Of course, the zealots will tell you the contrary, but heh, I've been mopping behind that kind of 'programmer' all fresh from school and full of STL crap for a few years.

  115. 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.
  116. Not complete enough by Anonymous Coward · · Score: 0

    The c++ stl is great as far as it goes but it doesn't compare to the standard libraries that come with other languages (java for example).

  117. Daylight savings time by Zathrus · · Score: 1

    struct tm.tm_isdst

    If it's set, it's DST, if not, it's not.

  118. Cons by Anonymous Coward · · Score: 0

    (1) Portability
    Portability isn't always great, especially with Visual C++. Plus VC++ gives hundreds of warnings when you use STL classes for no real reason whatsoever ("identifier too large"), making it hard to find real warnings.

    (2) Overhead
    People that use STL claim that it is fast. This isn't always the case. OLog(n) is great except when O is large. Plus templates tend to expand your code size, which can slow down runtime due to limited cache size. Some commonly used methods, like size(), are much slower than they should be for dubious reasons.

    (3) It's really hard to get the syntax right
    The syntax of many common things in STL is really weird. Sometimes you create objects containing single methods rather than simply passing methods around, for example. I constantly find myself Googling for examples.

    (4) Compiler errors
    Compiler errors with STL are horrible to read. It's really hard to figure out what's wrong sometimes.

    (5) Read Scott Meyers book
    Read the book. If it doesn't scare you off, then you'll do fine with STL. But remember that other programmers might not be as willing to put the time into learning it as you.

  119. 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 epine · · Score: 1


      I think small_dick must have done a lot of self moderation to warrant a 5 for that wad of premajaculate.

      90% of the ugliness in C++ is due to maintaining downward compatibility with C. That was a strategic decision from the outset, without which C++ most likely would never have become the subject of this thread.

      Beyond those defects, it really comes down to whether a programmer is patient enough to cope with static binding and dynamic binding in the same context. Tell me what Java has accomplished when Java has the same expressive power for static bindings.

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

  120. This is why I like Java by Jack+Greenbaum · · Score: 1
    All of the drawbacks mentioned above (code bloat due to specialization, lack of good docs, inconsistant template support in compilers, differing implementations) are exactly why I really like the Java Collections APIs.

    One implementation, well documented, threadsafe or not (your choice), consistant support. Yes, you suffer in performance and memory requirement compared to C++, but most software I write has a heavier weighting on time-to-implement vs run-time efficiency.

    So they aren't typesafe. Big deal. I almost always put things in collection from within a typesafe member function, so this really doesn't bother me. Having to cast to the type I'm assigning is annoying, but that is is what dyn-abrevs in emacs are for.

    I can't stand C++ and all of it's boroque(n) splendor. STL is just another layer of obfuscation.

    1. Re:This is why I like Java by Anonymous Coward · · Score: 0

      Offtopic.

      No one cares why you like Java.

  121. Debugging is FUN! by Gord.ca · · Score: 1

    I once tried using C++ STL for a programming competition. Had to write a simple HTML parser. I wrote the thing and it gave me a tonne of indeciferable error messages. Spent the rest of my time trying to track them down. It always felt like I'd have the thing done in a few minutes, but it turned out I had no idea what I had done wrong.

    ...so I never moved on to other questions, and got a terrible score. I now hate STL with a passion. (Actually I don't use C++ anymore...)

    --
    The opinons expressed are those of the voices in the author's head and are not necessarily those of the author.
    1. Re:Debugging is FUN! by Anonymous Coward · · Score: 0

      Ha, were you at the 2001 ACM programming competition too? I feel bad for you, one guy on our team died on the HTML problem too. He was using STL. He spent 3 hours on it. We finished one problem, yay!

    2. Re:Debugging is FUN! by Gord.ca · · Score: 1

      It wasn't ACM... it was the 2000 canadian computing competition (for high school; put on by UWaterloo)

      --
      The opinons expressed are those of the voices in the author's head and are not necessarily those of the author.
  122. A few annoying bugs by Anonymous Coward · · Score: 0

    First off, I would like to say that the general
    system is great, but there are a few _very_ dangerous bugs.

    Bug 1:

    list myList;
    list::iterator myIt;

    for(myIt=myList.begin(); myIt!=myList.end(); myIt++) {
    if (something about (myIt)) {
    myList.remove(myIt);
    }
    }

    -- run that above, and you'll get seg faults in _weird_ places, like a few iterators down the road -- i have no clue why.

    Bug 2:

    class something_complex{
    list blah;
    }

    something_complex *ptrs;

    int main() {
    ptrs*=(something_complex*)malloc(sizeof(something_ complex)*some_int);
    ptrs[0].blah.someoperation;
    }

    also gives a seg fault ...

    lack of good doc ... the ISO C++ 3.0 doc does NOT cover all the necesary functions, of if it does, its so disorganized that I don't understand it

    FXFX

  123. 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 joshwalker · · Score: 1
      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.)

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

      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.

      If you haven't yet, you should look at boost. They have a very useful smart pointer library.

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

      See the boost (http://www.boost.org) sharedptr. It works very well for handling it, as the STL is copy-based. Autoptr is pretty much exactly what you don't want. ... Or so I have experienced in my work with it.

    3. 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))"
    4. Re:The STL, by a longtime user by Arandir · · Score: 1

      I recently ported a X11/Qt application of mine to Windows. Because Qt is crossplatform, and I had extremely few unixisms, I expected no problems.

      The Qt stuff was completely effortless. The unixisms were simplicity. All that was kind of stuff was done in five minutes.

      But porting code that works under gcc-2.95.3 to Visual C++ 6.0 took about an hour. I wasn't using any GNU extensions. All of my code was ISO Standard C++. But VCPP choked on quite a bit of it. One example: if you declare a counter variable in a for loop, it remains defined until the end of the function, and not just until the end of the block.

      --
      A Government Is a Body of People, Usually Notably Ungoverned
    5. Re:The STL, by a longtime user by blank · · Score: 1
      are there actual facts that Herb Sutter and Stan Lippman are money grubbing sellouts? there were so many negative attacks like this on slashdot towards these men's image that i feel i must have missed the history of when these two men intentionally screwed people over for money. did that happen?

      i just want to be certain that either these men suck or that people are just being idiotic (which i'm all for).

      i know... i know.. take slashdot with a grain of salt...

      --

      bah. start over

    6. 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.
    7. 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))"
    8. Re:The STL, by a longtime user by Anonymous Coward · · Score: 0
      quote:
      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.)


      What complete and utter FUD !! Its true that VC6 has less than STeLlar support for STL but as the poster below said, it uses Dinkumware's implementaion, written by P.J. Plaugher and the problems are caused by VC6 lacking certain template features which was kind of unavoidable given when it was released.
      VC++.NET (VS7) has much much better template (and hence STL) support. In addition, MS has publicly stated that their goal for VC7 is to be completely standards compliant, which is why they also bought on Herb and Stan. They already have an internal build of the compiler that compiles Boost and Loki without any workarounds which I believe is a first for ANY compiler. It is slated to be released as a patch to bring VC upto VC7.1, probably around November.

      I know that this being /., I'll come off as being an MS apologist, but guys, give credit where credits due.
    9. Re:The STL, by a longtime user by blank · · Score: 1
      thanks. i read your post wrong.

      my brain is in a haze and this place is leaves a big bad taste in my mouth and i was a little tired with the personal attacks on people who i don't think deserves it.

      you are right, i need to relax.

      --

      bah. start over

    10. Re:The STL, by a longtime user by epine · · Score: 1


      Any criticism of C++ centered around experience with a Microsoft compiler is pretty much worthless.

      Microsoft's support of templates through version 6 was on a rough par with the support in Netscape 3.0 for cascading style sheets.

    11. 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?
  124. Compile Time Issues by StarkII · · Score: 1

    The STL is great, but it can be a bit of a pig when it comes to compile time. Heavy use of the STL ends up roughly doubling our compile times... even with very careful dependency manipulation. There is no good way to forward declare complex template declarations, so you usually end up including the stl headers in your .h files instead of in your .cpp files where they belong.

    There are some very clever template expansion tricks that can be used to do compile time calculation of certain mathematical functions that end up really inflating compile times as well.

    A really good tip for improving compile times is to search the stl headers to find their header guards (e.g. _STRING_, _ALGORITHM_) and in your code, put:

    #ifndef _VECTOR_
    #include
    #endif

    Even though the code in the header does not get compiled, it still has to be parsed to find the associated #endif. Wrapping your own #include is much more efficient.

    Yes, yes, yes, I know it does not work on across platforms, but it does not hurt the other platorms either, it just works like normal.

    --
    Jens Wessling
  125. one thing that is *not* a disadvantage by Anonymous Coward · · Score: 1, Funny

    is that STL "IS NOT PIRACY"

  126. Clear case for post annotations... by Lethyos · · Score: 0, Troll

    I think we all need to get CmdrTaco to impliment a post annotation system. Something like this was talked about back in the days of the Troll Post Investigation. We really need the capsity to go back and ammend posts!

    --
    Why bother.
  127. 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).

  128. Sparse matrices? by The+Evil+Beaver · · Score: 1

    I heard that there's no sparse matrix (or any sort of matrix) container in the STL. Where would one go for that?

    --
    Chris 'coldacid' Charabaruk Meldstar Entertainment
    1. Re:Sparse matrices? by Anonymous Coward · · Score: 0

      I heard that there's no sparse matrix (or any sort of matrix) container in the STL. Where would one go for that?

      for math:

      Blitz++

      for everything else:

      BOOST

    2. Re:Sparse matrices? by Frobnicator · · Score: 1
      A matrix is technically not a container, but a data type. I use the Intel Small Matrix Library matrix classes as the type, and the STL to store them.

      If you want to store objects by location in n-space (like a sparse matrix), you could use a set with the coordinates as the key. A dense storage matrix can be trivially implemented with vector classes, but you cannot to matrix operations on them.

      --
      //TODO: Think of witty sig statement
  129. first post! by Anonymous Coward · · Score: 0

    well, almost!

  130. Re:A few annoying bugs -- your own fault. by Frobnicator · · Score: 1

    I have to say RTFM. BUG 1: Your iterator became invalid once something was erased. In the specs: "List reallocation occurs when a member function must insert or erase elements of the controlled sequence. In all such cases, only iterators or references that point at erased portions of the controlled sequence become invalid." BUG 2: There's not enough information, but it doesn't look like an STL issue. As for the docs, I have seen several good sets of documentation on the STL.

    --
    //TODO: Think of witty sig statement
  131. Re:Not all compilers support it, god-awful comp er by scotch · · Score: 1

    Not disagreeing, but I've seen some compiler errors from straight C compilers rivaling that obfuscity. These are usually arising from the agressive use of really long complicated macros. This makes since when you consider that macros are used to acheive the some of the same functionality as templates in C++. Without the type safety, of course.

    --
    XML causes global warming.
  132. Re:Not all compilers support it, god-awful comp er by Avumede · · Score: 1

    Yes, I was referring to binary code, not c++ code. I really should double-check my posts for clarity.

  133. Recommending stlport. by SadatChowdhury · · Score: 1

    Apart from a bit of time you need to invest in learning how to properly use STL, I don't think there are any downsides. There are many ways you can write inefficient programs, using direct assembly language...it all depends on how good you implement your solutions. STL is a powerful tool that should help you, if you learn to use it well.
    While we are on the subject of STL, I'd like to recommend "stlport" (www.stlport.com). It is a somewhat more efficient implementation of the STL and works with most compilers (I have used it successfully with MS-VC++ 6 and Borland C++ compilers).

  134. Too bad typeof(X) not in C++ by Anonymous Coward · · Score: 0

    It would be nice to do this:

    std::vector v;
    //...
    typeof(v)::iterator i = v.begin();

    local typedefs are a workaround, but are wordy as you say.

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

    1. Re:Downsides by Matthew+Austern · · Score: 1
      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?)

      I'm not aware of any compilers, for IA-64 or for any other arthitecture, that do special things with std::valarray. My impression is that the people who care about high-performance matrix computation in C++ are spending more effort on things like MTL and Blitz than on valarray.

      It's a pity, in a way. The C++ standard was deliberately changed, in subtle but important ways, to allow implementers to do clever optimizations with valarray. But if any implementers have taken advantage of that freedom, I haven't heard about it (and I'm in touch with enough people so that I probably would have).

    2. Re:Downsides by David+Greene · · Score: 1
      With the STL, C++ has finally aquired a part of what Smalltalk and Java have always had: a library of base classes.

      The STL is a library of generics, not base classes. Unless you're talking about unary_function or something. Generally, one should not inherit from STL classes. Inheriting from traits classes is ok (encouraged?).

      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.

      This sounds like a second-system effect. Once your team got familiar with C++ and inheritance, the tendancy was to use it everywhere. Happens to everyone. :)

      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.

      My experience was exactly the opposite. Before I learned about the STL and templates, I was trying to shoehorn designs into inheritance heirarchies. Now templates are becoming the preferred method of expression -- the curiously recurring template pattern, for example, can eliminate virtual function calls. Andrei Alexandrescu presents a nice synthesis of generic and object-oriented programming in Modern C++ Design .

      --

    3. Re:Downsides by epine · · Score: 1


      The generic idioms and implementation blocks are so different from conventional OO structure that you naturally find yourself acquiring different stylistic preferences.

      Generic code is largely based on manipulations of types rather than values. Entirely different classes of mistakes are made manipulating types rather than values.

      My guess is that the people on your team who were most sensitive to layout issues where the members of the team who were most clued into the fundamentally different expressive nature of generic code.

  136. In my experience... by Anonymous Coward · · Score: 1, Interesting

    When things are working as designed, the STL can save you a LOT of headaches. But when something goes haywire, are you going to be able to debug the problem in the function named:
    ___erase__t7rb_tree5Zt4pair2Z6stringZ6stri ngZt4pai r2ZCt4pair2Z6stringZ6stringZ7mapelemZt9select1st1Z t4pair2ZCt4pair2Z6stringZ6stringZ7mapelemZt4less1Z t4pair2Z6stringZ6stringZ5allocPt14__rb_tree_node1Z t4pair2ZCt4pair2Z6stringZ6stringZ7mapelem

    This is how many STL function names will get reported, if you don't have a really good C++ name demangler (and yes, this is an example from a project I'm working on). Note that the problem might not be in anything in the STL, but a memory corruption could easily flatten something being managed by STL code.

    Some aspects of the STL can be overly constraining. I find it very unnatural to have to specify one and only one comparison operation that dictates the sort order of a vector. In C, if you want to sort things differently, you can hand a new function pointer to qsort(), but with the STL, you're kind of out of luck. How would you go about writing a (thread safe) program that allows the user to sort something according to run-time criteria?

    Some things simply cannot be managed appropriately by STL containers. For example, never try to use vector<auto_ptr<string>>. The semantics of the copy constructor of an auto_ptr are not compatible with the requirements of an object to be contained by an STL container (specifically, the copy constructor has side effects).

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

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

    1. Re:Some is way too verbose by Anonymous Coward · · Score: 0

      C++ would be well served by the addition of lamba functions so they could be embedded inside STL algorithms without requiring an awkward out-of-function function definition.

    2. Re:Some is way too verbose by hymie · · Score: 1

      You need to look into things like the lambda library.
      People are working the hell out of expression templates to let you write natural-looking expressions instead of explicitly using binders and such.
      Here's what it looks like:
      for_each(c.begin(), c.end(), cout << 2 * _arg1);
      The magic is that _arg1 is of a class which causes the whole cout << 2 * _arg1 expression to turn into a functor that doubles its first argument and sends it to cout. Not only that, but the people who are doing this are in close contact with (or *are*) people on the C++ Standards committee, so when the next version comes along, you can expect a lot of the kinks to be worked out.

    3. Re:Some is way too verbose by RovingSlug · · Score: 1
      Looks good. Could you provide links? Because, I found:
      • The Lambda Library for C++, last updated May 2000.
      • FC++: Functional Programming in C++, last updated July 2001.
      • FACT!, last updated September 2001.
      Definitely some good stuff in there, but considering their last updates, not exactly "working the hell out of". :/ Is it just that it's been stabilizing? Or, are there other projects out there I haven't hit on, yet?
  138. C++ + STL + BOOST = FORTRAN by Anonymous Coward · · Score: 0

    Scientific programming is slowly coming over to C++ due to the vast power of its template meta programming. BOOST is awesome. It matches or beats FORTRAN's BLAS in most tasks. No other computer language has anything nearly as powerful as C++ templates.

    If anyone even mentions Java in scientific computing circles they'd get laughed off campus. FORTRAN or C++ is used exclusively in this area.

  139. No overhead -- no usable error messages by Latent+Heat · · Score: 1
    My experience with templated stuff is that it is the greatest thing since sliced bread when it works, but compile-time error messages with templates can send you up the wall because the error messages don't tell you what went wrong unless you are a C++ uber-geek.

    I think the problem has to do with the macro-esque nature of templates -- where it finds the error is buried in some symbolic expansion that does not back map to tell you what you did wrong. In an unrelated topic, LaTeX (a bunch of TeX macros) has much the same unfriendliness to its error messages.

    For error handholding, interpreted good, anything macro'd or templated, very, very bad.

  140. Too good to be true? by Snebjorn · · Score: 1

    I've been advocating the use of STL on almost every project I've been on since 1998 - it really sounds like a great idea - and STL has paid me back with portability/upgrade problems almost every time.

    STL would be great if it actually worked between compilers/OS versions, but I still feel like I'm running a risk whenever I go for a solution based on STL instead of coding everything from scratch in C.

    /Snebjørn

    --
    Faster-Harder-Louder
  141. 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.
    1. Re:Is it just me.. by Anonymous Coward · · Score: 0

      The english speaking humans' ancestors stole words from many other languages. Thus confusing many living humans on word spelling and usage.

    2. Re:Is it just me.. by saddino · · Score: 1

      Even worse: "prolly" instead of "probably"

    3. Re:Is it just me.. by Bennn · · Score: 1

      Nope, it's not...'lose' has been bugging me for years now. It seems a simple algorithm - if you're under 30, you spell it 'loose'. I bet it's something to do with the big phonics vs real-words argument :)

  142. Re:Not all compilers support it, god-awful comp er by wurp · · Score: 1

    Yeah, I figured you probably knew what you were talking about, but was not at all certain that everyone else would.

    No need to check for clarity, that's what I'm here for ;)

  143. 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?
  144. 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.
  145. 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 Anonymous Coward · · Score: 0

      Try python and Java, the combination of these two very different (python is dynamic typing, Java is not) language is astonishing to accomplish a 3-tiered system, this is from personal experience, not "someone said so..."

    2. Re:This is what I like. by gkatsi · · Score: 1

      This response seems like you did not even read the post you replied to. C# and the rest of the mainstream languages (java, python, perl, whatever) can do none of the thigs that c++ can do.

      In c++ they look ugly, but at least they are doable. What the original poster wished for is a successor language to c++, which will support all the new programming techiniques that were made possible in c++, but in a much cleaner way.

      Of course, for all we know, the new language might as well be called c++ 2005. It's like the old saying "I don't know what language we'll be using in 20 years, but I know it's going to be called FORTRAN" (I forget who said it, though).

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

  146. * 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 David+Greene · · Score: 1

      It may not be faster than C, but the Blitz++ numeric library compares well with C/FORTRAN in terms of speed while allowing solutions to be specified in the problem domain rather than in the solution domain (i.e. multiplies matrices directly rather than writing loops or making function calls). This is worth quite a bit.

      --

    7. Re:* is faster than C (??) by MobyDisk · · Score: 1

      Simple: Take any existing C code. Add inline and const appropriately. Recompile. Bang, code is faster. If you have a really new compiler, you could also use the new restrict keyword when aliasing is not permitted.

      I know this is a cheesy example, but remember that this is one of the reasons C++ is provably faster than C. It has keywords that allow the compiler to generate better code.

    8. 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
    9. 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
    10. 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.

    11. Re:* is faster than C (??) by AstralSeeker · · Score: 1

      Precompiler directives.... it's a lot like a template you know... much weirder and undebuggable, but it's still possible to have that fast sort in C without recoding everything.

    12. Re:* is faster than C (??) by Anonymous Coward · · Score: 0

      Casting pointers is free isn't it?

    13. Re:* is faster than C (??) by Anonymous Coward · · Score: 0

      C has had const since 1989, and inline since 1999. Oh, and in C99 they added the restrict keyword to allow the programmer to specify that pointers of the same type don't alias. They don't have that in C++, yet.

    14. Re:* is faster than C (??) by epine · · Score: 1


      I can think of two cases which C++ wins out of hand right off the top of my head.

      qsort() versus sort

      sort wins hands down. sort inlines the comparison primitive. qsort must call the comparison routine via a function pointer.

      This has been documented many times with actual numbers.

      The second case is an efficient implementation of accumulate for floating point operands. If your machine has a multicycle latency for the result of a floating point addition (3 or 4 cycles is typical) you can compute the sequence sum faster by using three or four intermediate sums (adding a different term to a different intermediate on every cycle, then summing the intermediate values to get the final result).

      A hand coded loop in C with a single summand won't perform as well.

    15. Re:* is faster than C (??) by epine · · Score: 1


      This thread started off with a request for a real example of a case where C++ outperforms C. qsort is such a case. No one is saying that the efficiency of sort in C++ is the fundamental reason we chose to program in C++

      I chose to program in C++ because retains its efficiency at high levels of compositionality. This allows me to use more powerful abstractions without worrying that speed will become a serious problem.

    16. 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.
    17. 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.
    18. 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.
    19. Re:* is faster than C (??) by Anonymous Coward · · Score: 0

      The reason is simple: C++ allows you to force the compiler to generate specific code for your particular use.

      See for example the sort() template function that takes the comparision as an inline argument instead of function parameter, or some other way of function-call indirection like inheritance. The immediate benefit is that the compiler can even chose to inline the comparision function, which is evidently a big save for simple comparision functions.

      Other even more interesting examples can be found in mathematics code. E.g., consider a matrix object Matrix which stores its data in an embedded array:

      template
      class Matrix
      {
      double data_[x * y];
      };

      In C, one would need to do a malloc() and free() operation to reach something similar (and as generic) on construction and destruction, and even worse every access to data_ would need one more indirection.

      C++ Code Monkey

    20. Re:* is faster than C (??) by gmarceau · · Score: 1
      I'm offering your here some supporting evidence that C++ is slower than C : The Great Computer Language Shoutout, a work of hard labor and love.

      The short story is, even though the combinaison of C++-to-C compatibility and C++ templates should make C++ faster, the numerous implicit memcpy's and copy constructor calls behind C++'s syntax makes the promess painstaking to realize in all but very small programs. Thus, even the dedicated and competent programmer that created the gcls could not get to C's speed.

      --
      This post was compiled with `% gec -O`. email me if you need the sources
  147. 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.

    2. Re:STLport works with both MSVC and Embedded MSVC by Anonymous Coward · · Score: 0

      Everything but Streams, that is !

      One of the most important parts.

      Note, if I'm wrong, and you were able to compile the streams, please say so.. heheh

    3. Re:STLport works with both MSVC and Embedded MSVC by epine · · Score: 1


      Was that the typical length of your problem report?

  148. 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));
  149. 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.

    1. Re:Error messages can be made readable by Anonymous Coward · · Score: 0
      I'll never have to deal with another crackpot programmer's homegrown, poorly commented dynamically-sizing array class again.

      Hear, hear! I'm was just maintaining some code today that a guy here put together in just the last year.

      Get this: He wrote his own string class!

      Apparently, when we told him that MFC was verboten he decided he couldn't live without some kind of wrapper for strings, and didn't even bother to look in the STL or even ask. He even used these abominations in his APIs.

      I could just scream. I have no idea how much time he wasted perfecting these things, or how much time we waste trying to maintain code containing these horrors.

  150. 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
    1. Re:STL is only as good as you... by Snebjorn · · Score: 1

      The advice "get a good compiler" obviously makes sense - and I've seen it being followed in a corporate environment.

      The next step is to get two or more compilers to actually agree on what the STL definition really means.

      /Snebjørn

      --
      Faster-Harder-Louder
  151. Peformence by Codex+The+Sloth · · Score: 1

    Usually (but not always) only a problem when you are doing server side work but RWCString uses copy on write (see here). You have to muck around with the mutex pool size to really get this to work though...

    --
    I am not a number! I am a man! And don't you ... oh wait, I'm #93427. Ha ha! In your face #93428!
    1. 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.
  152. 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

    1. Re:RougeWave? by Bigboote66 · · Score: 1

      For a surprise, go to www.rougewave.com and find out what they sell.

      I wonder if the guys at Rogue have decided that the coolness of the name has been trumped by the hassle of correcting everyone.

      -BbT

  153. GJ A Generic Java by Modular · · Score: 1

    I'm looking forward to somebody starting over some day and coming up with a language that supports generic programming as well as C++, but which doesn't have the terrible syntax of C++ templates. It must be possible.

    GJ is that language, A Generic Java Language Extension . Note that the page contains this link, Sun has put forward a proposal to Add Generic Types To The Java Programming Language, based on GJ.

    I first came across GJ in an article, GJ A Generic Java, in the February 2000 issue of Dr. Dobb's.

  154. C++ + STL + BOOST + BLITZ++ .gt. FORTRAN by Anonymous Coward · · Score: 0

    BLITZ++ is the math library - not Boost.
    I'm such a fucking idiot.

  155. 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?
  156. Re:Not all compilers support it, god-awful comp er by macrom · · Score: 1

    There was an article in the C/C++ Users Journal a year ago testing for compiler conformance. No compiler made 100%. The areas that some of the more advanced compilers lack are probably deep, dark recesses of the STL you'll never use, but there are still gaps in the implementations.

  157. Re:Why is inheriting from an STL class such a bad by Anonymous Coward · · Score: 0

    Why not declare iterator as a typedef in MyClass?

    typedef vector::iterator iterator

    in a public section of MyClass.

  158. 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 Malc · · Score: 1

      What about the IO streams - they seem to employ inheritance?

    2. Re:The STL is not OO by Anonymous Coward · · Score: 0

      iostreams is part of the standard library, not part of the STL. The STL is part of the standard library too.

    3. Re:The STL is not OO by vivarin · · Score: 1

      The STL doesn't use inheritance much, but it certainly uses polymorphism to the nth degree -- there's no interface difference between many of the container templates, for example.

    4. Re:The STL is not OO by IkeTo · · Score: 1

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

      Everything in STL is compile-time determined. Then there is no need for using OO concepts like polymorphism. I'd rather count generic programming as a concrete part of OO programming, and say that STL used the alternative way to do OO.

    5. 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.
    6. 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.
  159. Book title by lovelaceAtWork · · Score: 1
    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.
    I highly agree, but when you go to look for the Josuttis book, remember that the name is: The C++ Standard Library: A Tutorial and Reference (no "Template" in the title).
  160. 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

  161. 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?
  162. To all the VC/STL developers in the room.... by Anonymous Coward · · Score: 0

    I have just one thing to say that makes working with STL a rather intimidating experience initially:

    4786

  163. Not going to miss Rogue Wave by Anonymous Coward · · Score: 0

    They were great back in 1993, but have done little to keep pace since them. They even broke the APIs of their own RW container classes between the STL and non-STL versions of their Tools. Does that make any sense at all? Their libraries are supposed to _shield_ me from changes - that's why I paid big bucks for their libraries in the first place. Who gives a shit if I happen to use STL or not - why are the arguments to their classes different as result of configuring with STL or not? I should not _change_ my code when I upgrade their library. As such, they add little or no value to the enterprise. They rely on thier customers to find (and sometimes fix) their thread bugs. Now they want a per-program and per-developer and per-CPU royalty - forget it. Thanks for all the memories!

  164. About maps... by the_skywise · · Score: 1

    iterating over a map is about the same cost as iterating over a list. A map is derived from a Set, which is pretty much a sorted list with an added hash table for quick lookups. The performance hit on a map comes on insertion which is much slower than inserting into a list.

    While I agree that the standard interface hides the complexity, I personally think that's a good thing. The bulk of the code written will be of a run once variety, whereas a central core will most likely require custom code anyway, indicating less of a need for a "standard" library.

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

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

    5. Re:About maps... by Anonymous Coward · · Score: 0

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

      You don't need to care about the implementation per se as much as the user-visible performance of that implementation; that's why the various STL classes have performance as part of their description, so you can make a reasonable tradeoff. You don't (hopefully!) need to know how a map vs a list is implemented, but you do need to have read the description of those classes to see what kind of performance guarantees each one gives you.

    6. Re:About maps... by ejasons · · Score: 1
      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.
      No, the first level of optimization should always be to optimize the *algorithm* used, before you try to do more "micro-optimizations". If you're inserting elements into the middle of an array (vector), then your performance is going to suck. On the other hand, if you're jumping around through a linked list, the performance will likewise be poor.

      The beauty if STL is that you can change your underlying data structure, to change the characteristics of your code, without having to go through and rewrite the code. So, if you want to write a data structure that has good performance for both insertion and random access, you can do so, without having to alter the code that uses the data structure.

    7. Re:About maps... by Anonymous Coward · · Score: 0

      The performance of a hash function most certainly can be guaranteed. Look up dynamic perfect hashing for examples of guaranteed time bounded hash functions. The drawback is that tightly bound hash functions tend to have space or code complexity tradeoffs.

    8. Re:About maps... by Ahenobarbus · · Score: 1

      You are confusing things.

      Time bounds on hash tables are even better than maps. It's constant time lookup. You don't even have to amortize to get the constant time. It's really constant, each and every time.

      Where you do have to amortize is when you decide to resize the table. But, with amortization, hash tables are still constant time insert and lookup.

      So, why are sorted containers implemented with red-black trees? Because they are sorted. Hash tables have no notion of relative order. Your item is there, or it's not. It is quite difficult to find the next higher or lower item. When you want efficient, but sorted data, you need a tree datastructure of some sort.

      Michael

      --

      ---
      It's all fun and games until someone gets hurt. Then it's just fun.
      ---
    9. Re:About maps... by Anonymous Coward · · Score: 0

      No, worst case performance of a hash-table lookup is linear. This is in the limit where there are more elements in the hash table than buckets, so that many keys hash to the same value. Essentially, you end up doing a linear search through the list of elements that have the same hash value.

      The only time the lookup will be truely constant time is when there is at most one element per distinct hash value. But lookup the 'birthday paradox', the size of hash table required for this is enormous.

      Rehashing the container is linear in the number of elements. If you grow the number of buckets geometrically (eg, double the size each time) then you can get amortized constant time insert while maintaining a constraint of N% full.

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

  165. 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!
  166. 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
  167. Meta Programming - Google for OpenC++ by Anonymous Coward · · Score: 0

    One project I'm working on uses STL for containers while OpenC++ writes the stream insert/extract. The result is too beautiful for words, but one day maybe you'll be able to play it :)

  168. Re:Not all compilers support it, god-awful comp er by Heinrich · · Score: 1
    Using the STL and templates, you will tend to have less code, not more.

    Not necessarily. Just consider the alternatives to templates and forget for a little moment about being enforced to templates in C++ because of a missing general base class (like Object in Java). If you have templates, you will get duplicated code for each different template instantiation. Code duplication, however, does not happen if you write some general code that works for some base class. Take List in Java, for example. You have the code of List just once even if you have several lists, one with apples and the other with bananas.

  169. 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
  170. 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 Garen · · Score: 1

      Its also worth mentioning that recent implementations of sort in the C++ STL use the introspective sort algorithm instead of quicksort, which gaurantees the worst-case performance isn't quadratic.

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

    4. Re:One example by epine · · Score: 1


      ] There being very few programmers quite experienced in both ...

      That's a huge laugh. I can tell you hang with an under 30 crowd. In my generation (we're not all extinct yet) there are few hardcore C++ programmers who weren't once upon a time masterful C programmers. And it's not like we forget, either. Unfortunately, we're constantly reminded of all the defects of C because C++ leverages so many of them.

      There are many excellent system programmers out there who work almost exclusively in C (I'd include the Perl internals as system programming).

      There are far fewer excellent application domain programmers who prefer C as their primary language. Those who wanted sharper knives went to C++; those who wanted more conformity went to Java; those who wanted to retire a few years early returned to COBOL.

  171. WTF by Anonymous Coward · · Score: 0

    Know why I like Java?

    1. Re:WTF by Anonymous Coward · · Score: 0


      >java RemoteURLImpl
      RemoteException: RemoteException occurred in server thread; nested exception is:
      java.rmi.UnmarshalException: error unmarshalling arguments; nested exception is:
      java.lang.ClassNotFoundException: RemoteURLImpl_Stub
      java.rmi.ServerException: RemoteException occurred in server thread; nested exception is:
      java.rmi.UnmarshalException: error unmarshalling arguments; nested exception is:
      java.lang.ClassNotFoundException: RemoteURLImpl_Stub
      java.rmi.UnmarshalException: error unmarshalling arguments; nested exception is:
      java.lang.ClassNotFoundException: RemoteURLImpl_Stub
      java.lang.ClassNotFoundExcepti on: RemoteURLImpl_Stub
      at sun.rmi.transport.StreamRemoteCall.exceptionReceiv edFromServer(StreamRemoteCall.java:245)
      at sun.rmi.transport.StreamRemoteCall.executeCall(Str eamRemoteCall.java:220)
      at sun.rmi.server.UnicastRef.invoke(UnicastRef.java:3 54)
      at sun.rmi.registry.RegistryImpl_Stub.rebind(Unknown Source)
      at java.rmi.Naming.rebind(Naming.java:160)
      at RemoteURLImpl.main(RemoteURLImpl.java:43)

      oh yea, that's Much better!

    2. Re:WTF by noom · · Score: 1


      Q: WTF?

      A: That's not a compilation error, it's a stack trace from a run-time error.

      And the problem is probably that you don't have the output from the RMI compiler in the classpath for either the rmi registry or the jvm.

  172. 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 ajs · · Score: 1, Flamebait
      You were trolling [...] Anybody who recomends Python over C++ because C++ is a "bad" language but Python is a "good" one knows nothing about language theory
      I don't think I could have uttered anything quite so inflamitory and unsupported if I'd tried.

      Dear Troll, asside from your "whitespace is evil" rant (which I understand, but agree with your vehemence on), please explain why you feel that C++ is a well designed lanugage. Please include in that explanation the four casting operators and the ambiguities in constructor invocation vs casting operations.

      I posted because I feel that the question the article asks is incorrect in its assumptions. I was not trolling. If you do not agree, but do not wish to be "baited", don't respond. It's that simple.
    2. Re:er... "horseshit" by Anonymous Coward · · Score: 0

      dude, you even know what is a troll?

    3. 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
    4. 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}."

    5. Re:er... "horseshit" by daecabhir · · Score: 1
      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.

      Truer words have never been spoken. I sat in on a presentation by the author of Python earlier this year, where he went through an introduction to the language, and covered its "strengths". I just sat there thinking to myself "Please tell me he isn't serious? The last language I used that cared about column spacing was COBOL!!". And what is this crap about not having an explicit begin and end delimiters/statements for blocks of code being a "good thing"? Blank lines as terminators of blocks of code is just terminally brain damaged - it is just one more thing to make the code hard to read, and to piss me off in the interpreter because I hit a blank line when I didn't want to. No thank you - I'll stick to languages with more mature syntactical structures.

      --

      -- daecabhir (this mind intentionally left blank)
    6. Re:er... "horseshit" by chfleming · · Score: 1


      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.


      I am afraid I cannot follow you, because although you claim that this code is legal in "C", there is no "new" in C, as you must use malloc. Also "A()" makes no sense.

      Although I know what you are trying to communicate is in the second line, I do not trust any of it, because it is not C.

    7. Re:er... "horseshit" by fredrik70 · · Score: 1

      If one stick to ANSI C one is damn portable, just a recompile away...

      --
      if (!signature) { throw std::runtime_error("No sig!"); }
    8. 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.

    9. Re:er... "horseshit" by asincero · · Score: 1

      How can you not follow him yet know what he is trying to communicate?

      The point he was trying to make is that C pretty much allows you to cast an object of one type to some other type. The newer C++ cast operators do not.

      However, if you need the freedom the older C cast operation allows, theres nothing stopping you from using them...

      - Arcadio

    10. Re:er... "horseshit" by IBitOBear · · Score: 1
      First: The original question was (paraphrased) "Is C++ a well designed language?"

      Your Response to my position:

      The idea that everything exists in a language for a well-defined, unique reason is hardly a defense of the language DESIGN.


      Hello... McFly.... In point of fact the design of anything that *IS* *DESIGNED* is based on the core reasoning behind the elements of the design. When there is no core reasoning it is not designed it is "chance". To then understand the *DESIGN* instead of the *FORM* you must be able to access the design and not just the form. Saying "I don't like the way this is, it is porly designed" is logically junct. If you choose not to process the "why" of a design your assertions about the "what" of the form are, well, uninformed.

      Consider: "Dude, this is a terrible ashtray." "DUDE! That's not an ashtray, it's a coffie mug."

      Your entire position is that the language isn't sufficently lacking in complexity for your taste.

      You seem incapable of processing the basic point, so I'll say it again.

      It seems that you personally find C++ insufficently simple for you to internalize. Fine. You then go on to postulate that since it is too complex for you it must be too complex for anybody to use safey. That is unsupported and unsupportable. Just because it is too complex for you (or your personal taste) doesn't a-priori then mean it is too complex for everybody. The tool analogy holds. This is not a tool for people who wish to avoid complexety. It is a tool for people who need (or just "want" but that is a bad reason 8-) the power that is bought at the expense of that complexity.

      Period.

      And yet you persist:

      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?


      You suffer from a relative lack of understanding. The fact that there are many books which explain a concept doesn't infer that each or any one person needs to consult many books to find understanding. It only means that the topic is adequately covered elsewhere so needs not be covered here.

      The fact that you only refute odd corners of arguments and chose to do so at disproportionate lenght is itself revealing.

      Your arguments are biased (of course all arguments are [see definition of argument 8-)]).

      The fact that your "conclusions" are not particularly supported by your arguments is the true test.

      C++ is a complex language that lets you do things more effeciently than many (most?) others. That power is bought at the price of that complexity. It is not untennable or unworkable in and of itself. The people who are not up to the skill, or need, to persue it are invited to not do so.

      The following three absurdities are DIRECT analogies of your proposition:

      Shouldn't the SCUBA gear be simple enough that you any swimmer can use them without the need to be trained to dive?

      Shouldn't the scalpel be simple enough that you can opperate on the human brain without having to do more than basic med school?

      Shouldn't a 767 be simple enough that any general avation pilot (you know single propeller plane etc) could fly it?

      Finally, your assertion "C++ is a very good accedemic exploration of the value of C as a high-level language" is spurious. You toss this in as a "conclusion" without really connecting it to anything except a vague intimation of danger. That is a classically cheap closing technique you would be penalized for in any formal debate. Used imporperly many things are dangerous. Used properly many dangerous things are indespensible. (See "the family car" 8-).

      "At what price safety?" -- attribution unknown.
      --
      Innocent people shouldn't be forced to pay for inferior software development.
      --"Code Complete" Microsoft Press
    11. 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".

    12. Re:er... "horseshit" by cduffy · · Score: 1
      The fact that there exists a well reasoned explanation of why these things exist most certainly is a convincing defense.

      No, it isn't. Let me give you an example from a totally different field to explain why.

      One of the problems with modern (US) constitutional law is that the accepted standard for determining the ability of the federal government to take some action is not that this action be one of those explicitly granted within the enumerated powers, but rather that it have some rational basis in the legitimate powers of government and not be explicitly prohibited elsewhere.

      Having a rational basis isn't exactly a hard standard to meet -- anything that any reasonably sane person would ever want to do has some sort of rational basis behind it.

      Similarly, there's some "rational basis" for having any existing language feature -- if there were no well-reasoned defense for a feature, why would any language implement it at all?! Having a "well-reasoned defense" does not mean that this defense has been weighted against simplicity, ease of implementation, &c., either individually or in sum; and putting in every feature for which there exists some "well-reasoned defense" is a recipe for disaster. Simplicity should come before feature completeness -- something evidently forgotten in the design of C++.


      One last note: You mention LOC count of a resulting program as one measure of a language's clarity. I agree that clarity is supremely important, and that LOC count is a good measure. Might I mention that C++'s LOC counts tend to be absolutely hideous compared to most other languages out there? Type-safety or no, Python code (with a good test suite) is a far better solution than C++ if ones' goal is readability. Java is a much better solution if one wants safety (compile-time and otherwise). Scheme is a much better solution if one wants very short LOC counts (and is facing a problem appropriate to the language -- some are, some aren't, but one can't recognize the former unless one knows it). C is much more portable (my company deals with a great many embedded platforms where no working C++ compiler or standard library exists). C++ tries to do very, very much but excells at very little, and so it's only rarely I find it to be of use.

  173. 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?
  174. 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
  175. 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.
  176. hmmm... by Anonymous Coward · · Score: 0

    There is NOTHING that can reach the speed of C/C++ code.

    I don't like every feature of C++ either, but it's not _that_ bad and the STL is very good for the most part. If you are working with any type of application that requires maximum user responsiveness or pure computing power then you can NOT beat C/C++. I would argue that every application should run at near the maximum possible speed afforded by the computer, I'm sick and tired of waiting on the computer to do stuff.

    1. Re:hmmm... by wackybrit · · Score: 1

      There is NOTHING that can reach the speed of C/C++ code.

      Wow, yet another display of total ignorance about compilers. Just because something is written in a variant of C doesn't magically mean it'll compile down to a tighter program. C encourages you to program in a tighter fashion, but it's all down to the compiler at the end of the day. A good Pascal compiler could easily beat down a mediocre C compiler any day.

      And to your point.. yes, assembly language can match the speed of a compiled C or C++ program, so yeah, you're wrong.

    2. Re:hmmm... by Anonymous Coward · · Score: 0

      Quite a few compilers for quite a few different languages from lisp to caml to fortran and everything in between meet or exceed the speed of C/C++ code. Why wouldnt they?

    3. Re:hmmm... by Anonymous Coward · · Score: 0

      I don't think so. They just don't. You'll have to prove to me anything else because I haven't seen it.

      Do you have any idea how hard it is to make a non-trival O'Caml program that runs as fast as the equivalent C/C++ program? I should know, I'm a big-time fan of O'Caml. I really like functional programming in general but I have never seen any functional language or compiler that can create non-trival code that is as fast as C/C++. Don't start quoting "the great language shootout" because all of those programs are trival and do not represent real life. Even if you do take a look at those benchmarks, there are only a tiny few where O'Caml is faster and those O'Caml programs have been tweeked to the max (lots of time spent fixing them) where the C/C++ program hasn't been tweeked at all and would easily still beat the O'Caml program if they were.

      Lisp has similar problems, don't get me started.

      True that Fortran can do some pure math stuff faster than most C/C++ code if the C/C++ code hasn't been tweeked. But you CAN tweek the code and achieve the same speed or faster than FORTRAN.

      The thing is, C/C++ almost converts directly to assembly language. You can't get any faster than that.

    4. Re:hmmm... by Anonymous Coward · · Score: 0

      Oh come on. It is not "all down to the compiler". C/C++ give you flexibility to write "high level assembly", you can make it fast by being a good programmer. Of course it won't magically compile down to the fastest program, but in general C/C++ are the fastest languages (other than sometimes assembly) out there, period.

      Yes, assembly language is as fast or faster than C/C++. Although some modern compilers can generate better code than hand-coded assembly (Intel's compiler for example; with its use of MMX, SSE, etc., instructions).

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

  178. Smartpointer information? by Anonymous Coward · · Score: 0

    Does anyone have links to good implementations of smart-pointers?

    Yes, yes, I know all about the Boost C++ stuff, I'm looking for other (possibly better) implementations.

    I need high performance.

    1. Re:Smartpointer information? by Anonymous Coward · · Score: 0

      Try YourAss::pointer for highest performance.

    2. Re:Smartpointer information? by Anonymous Coward · · Score: 0

      I haven't seen that library, could you provide more information?

      Or were you making a joke of some sort?

  179. Templates are bad programming style by Anonymous Coward · · Score: 0

    Templates and other C++isms lead to write only code.

    Don't use templates.
    Don't use implimentation inheritence.
    Don't use operator overloading.

    Otherwise your code will be an unmaintainable pile of shit.
    Look at openh323 for an example of this.

  180. Re:Not all compilers support it, god-awful comp er by NorthDude · · Score: 1

    WARNING
    Debugging STL errors can cause fatal heart diseases.Health Canada

    --


    I'd rather be sailing...
  181. 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...

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

    1. Re:Well, based on my experience with it.. by zander · · Score: 1

      Hi Rob.

      for the non GPL apps (most in the world out there, I know) you have to option to buy a licence from www.trolltech.com quite cheap as well.

      Qt certainly gets my recomendation over STL by far!

      Cheers!

  183. Team work by Aaliyah · · Score: 1

    I work for a large firm (~800 employees) of which about 30 are full time software professionals.

    I find that one major issue with using STL is that is not part of the C++ "language". That means that someone who says he/she knows C++ does not necessarily know STL.

    This means that I have to avoid using the STL when my code is likely to be modified, read, fidddled with etc by other folk on the team.

    This gets done qutie a bit and more importantly will be done when I leave the firm ...

    In the case of say Perl or LISP (which admittedly do not compare directly) you get Hashes and Lists as part of the language itself.

    Thus anyone who says he/she knows Perl /LISP knows about lists and hashes. They can be ued in peace.

    Further having a list/hash as part of the language itself would possibly mean a significant reduction in the size/style of error messages and the like.

    I still use the STL whenever I can and hide behind interfaces (when they can be well defined in advance) or when working on small individual projects.

    While I cannot say this with any real confidence, I think that understanding why someone's chosen to use container x and not why .... i not well commented .... is hardly transparent either.

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

    2. Re:Team work by Sabby · · Score: 1

      I know C++, I do not know the STL. The STL did not exist when I learned C++. I learned it back in 1992, when it was still being finalized. In addition, I never learned about namespaces, some of the rules changed, and a whole host of other problems. It makes it hard for me to convince people I know C++. I do. I use Rogue Wave and code in C++ sometimes. And I use Java other times. And perl. And VB. It makes it hard to keep everything perfectly straight, so it makes it hard for me to convince people I know C++ sometimes.

  184. Generic Java? by Anonymous Coward · · Score: 0

    Does anybody here have comments about the state of generic programming in Java? I know a bit about GJ, but that's about it.

  185. 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.
  186. 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().

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

  188. Java will have generics by shodson · · Score: 1

    Sun is working on adding generics to Java, hopefully by JDK 1.5.

  189. people who only know STL by blakieto · · Score: 1

    Asside from the code bloat and lack of control over memory allocations, a big problem I've had is working with programmers (usually fairly fresh out of college) who were taught how to program with STL and we find that they can't program without it! They are too used to the hand holding and don't know the algorithms they are using to begin with. I also grit my teeth every time I hear the "never write a linked list again!" quote... that dismays me every time! I wrote my last linked list (in C) back in 1985- and I've been using that "linked list management" code ever since. It strikes me that when people learn something like STL, they shut down their brain from ever thinking about the problem that STL was created for in the first place. A long time ago I built a set of "personal programming" routines that handles everything that I encounter during my programming. I understand this logic and I can fix and extend it as needed. People that start with STL never get to develop such expertise over their "bag of STL tricks" since they did not write it to begin with, can't debug it even of they had to and find themselves shit out of luck should they find themselves in an environment that does not have "their" STL implementation.

  190. 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 Matthew+Austern · · Score: 1
      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.

      You're confusing specification with implementation. The C++ Standard doesn't say whether or not std::basic_string uses reference counting. Some implementations do, some don't. The GNU implementation does, the older Dinkumware implementation does, the newer Dinkumware implementation doesn't, the SGI implementation (which I wrote) doesn't.

      As a general rule, my impression is that newer STL implementations have been moving away from reference-counted strings and towards the "small string optimization". Experience has shown that reference-counting is much more bug-prone than one might expect, that it doesn't provide as many benefits as it seemed to at first, and that its behavior, when you poke at corner cases, can be surprising.

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

  191. 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.
  192. For reducing code bloat, take a look at this page by Anonymous Coward · · Score: 0

    Code bloat need not be a problem of using templates. If you look at

    www.elis.rug.ac.be/~brdsutte/squeeze++

    you can see that we are able to reduce the code size of real-life programs (e.g. LyX) using a lot of templates by 60%. This is done by compacting the programs after they are linked, applying aggressive whole-program optimization and code abstraction techniques. There is a specific manuscript on the page as well, on how to reduce the code bloat coming from the use of templates.

    Cheers,

    Bjorn De Sutter
    Ghent University

  193. Side question by Second_Derivative · · Score: 1

    Are there any real practical compiled languages out there other than C and C++? serious question here. I want to write a fairly high performance app, what lang do I use? C isn't that great to be fair, it's standard library is a joke and doing tons of memory management isnt really up my street. This leaves the lesser of two evils C++. Java is... not that great cause it takes forever to load and tons of stuff is done on the heap (please don't flame me Java programmers, for now all I care about is that most people regard Java as slow whether or not that's justified ... that and it's controlled by one company anyway which I dont much like either). Python and Perl require interpreters so you need to have the whole shebang installed on the client's system and... well, let's be frank here it just looks extremely unprofessional if it isn't a CGI script. Someone hit me with a clue-by-four if I'm talking out of my arse or if not, tell me what decent compiled languages exist out there =)

    1. Re:Side question by Anonymous Coward · · Score: 0

      There is nothing like what you want. Your best bet is Java. It's a nice modern language without much cruft. Sure, it's little slow to start, but once the program is running you can't tell the difference between the Java program and a native program (assuming you have a computer made within the last 5 years).

  194. The Reason VC6's STL is buggy by jnv11 · · Score: 1

    Dinkumware, Ltd. was the company that Microsoft contracted with to write the library files for VC++ 4.2, 5, and 6. Due to a lawsuit involving Dinkumware and not Microsoft, the library was not updated beyond the July 1996 draft standard until VC++.NET was released, which was after Dinkumware trounced Plum Hall, Inc. in that lawsuit. By the way, Dinkumware has a page detailing all the known bugs of the July 1996 draft implementation and how to fix them here.

    1. Re:The Reason VC6's STL is buggy by NewIntellectual · · Score: 1

      Dinkumware also sells an inexpensive drop-in updated replacement STL. I bought it, it's worth it if you do serious programming.

  195. Re:Not all compilers support it, god-awful comp er by ComputerSlicer23 · · Score: 1
    What, you tried to a use a list::iterator where you should have used a list.

    It occurred on line 109 of readply.cpp? Now I'll grant it took 30 seconds to decode, mostly because you appear to have lost some characters in posting to slashdot and the character wraps at odd places.

    The really hard part was finding the 'to non-scalar type' in there to find the start of the second type. It isn't hard once you get use to it.

    Kirby

  196. STL doesn't handle Unicode/wide-char by Weyoun · · Score: 1

    STL is useless for Windows programming for two reasons:

    1. Many of its classes that input or output strings are only designed to work with ASCII. If you want to do anything with Unicode, forget it.

    2. std::basic_string has no CASE-INSENTIVE comparison routine. This is absolutely necessary for doing anything with Windows pathnames. Again useless.

    1. Re:STL doesn't handle Unicode/wide-char by Matthew+Austern · · Score: 1
      Many of its classes that input or output strings are only designed to work with ASCII

      Which classes do you have in mind? std::basic_stringbuf (and the wrappers basic_stringstream, basic_istringstream, and basic_ostringstream) all work with generalized basic_string, which can be instantiated for narrow or wide characters. All of the I/O classes, e.g. basic_istream and basic_ostream, work with general characters: again, both narrow and wide. std::bitset contains a stringification function, and, again, it outputs a general std::basic_string and doesn't assume narrow characters. There are a very few places in the library where narrow characters are built in, but they're many fewer than someone who's reading your comment might think.

      std::basic_string has no CASE-INSENTIVE comparison routine

      Indeed, and there's a reason for that. basic_string doesn't know about locales, and case-insensitive comparison is meaningless except in the context of a particular locale. (Quick quiz: if you're doing a case-insensitive comparison, is the one-character sequence 0x00df equivalent to the two-character sequence 0x0053 0x0053?)

      Case-insensitive string comparison is one of those subjects that sounds simple at first, but that gets more and more complicated the more you learn about it. See my article in the May 2000 C++ Report (not on the Web, alas, but it's reprinted in Scott Meyers's Effective STL) for an introduction to why this is hard.

      I don't think the right approach to complexity is pretending it isn't there.

    2. Re:STL doesn't handle Unicode/wide-char by Tjp($)pjT · · Score: 1

      Don't forget about IOSTREAMS and LOCALES which are also part of STL. They support wide characters, case insensitive sorting locale based sort orders, etc.

      Also, as to Unicode characters, very few libraries handle them properly, it is not just a matter of handling 16 bit representations. You also want byte order to be considered for I/O, escape characters, composite characters, equivalent characters, UTF-7, UTF-8, and UTF-32 (the only completely unfolded representation) in addition to UTF-16. Used properly it has some of the best Unicode foundation support.

      --
      - Tjp

      I am in wallow with my inner money grubbing capitalistic pig. ... Oink!

    3. Re:STL doesn't handle Unicode/wide-char by Anonymous Coward · · Score: 0
      "std::basic_string has no CASE-INSENTIVE comparison routine"

      That's why it's called "basic::string", you moron.

  197. 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.
  198. Re:GJ A Generic Java is slow by Anonymous Coward · · Score: 0

    Too many slow Java casts. The IBM Jikes VM (formerly named Jalepeno) gave up on GCJ because it produced too slow code. They hand roll their own Java templates with a custom utility they wrote.

    By the way, GCJ cannot templatize builtin types (such as int) which makes it completely useless for any serious development.

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

    1. Re:/. is a skewed sample by blank · · Score: 1
      i would mod you up a point if i had any moderation points.

      templates alone are really fascinating. i had heard all these terrible things about templates being a pain and how C++ can blow off your leg that i was very skeptical about C++. it was until i found out what templates are and what Generic Programming is that i started to apprecciate C++. thus i like the STL.

      --

      bah. start over

  200. Use the source Luke .... by Anonymous Coward · · Score: 0

    The big disadvatage of the STL, try reading the source to find out what the bug is, or just how a certain part works.

    I've seen deliberately obfuscated "C" code that's
    clearer.

  201. 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!
  202. exactly by Anonymous Coward · · Score: 0

    he pretty much states clearly that he is an ignorant monkey in no position to pass judgement, got to love slashdot!!!

    1. Re:exactly by Anonymous Coward · · Score: 0

      Agreed. A +1 interesting means something here? For a site that supports free speech goes to hides speech from "anonymous" posters, while even a troll gets read with a +1 interesting.

  203. Re:Not all compilers support it, god-awful comp er by Heinrich · · Score: 1
    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.

    That is your private terminology but not that of the field. The final phase of a compiler is called code generation and the result is code. Yes, code has multiple meanings and this is just one of them. For this reason, compiler writers (like me) prefer to speak about source text for the input of a compiler to distinguish it from the code which is the preferred term for the output of a compiler.

    And if you don't believe me, look it up in the Jargon:

    code n. The stuff that software writers write, either in source form or after translation by a compiler or assembler.
  204. 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.

  205. Java is even less standard though! by unsinged+int · · Score: 1

    Come on...if you compare the STL to Java for most programs, the STL wins hands down. Ever looked at the consistency between the Java classes that Sun supplies? Class A will have a method called M1 that does something and class B will not have a method called M1 but instead called M2...and both do exactly the same thing! Did Sun assign each programmer to a class and have them write each one without talking to each other?

    I actually use Java for some things, but with the class documentation open in a web browser at all times since it's so hard to remember the inconsistent naming. I think they should just deprecate half the methods, switch to common names, and then actually remove deprecated methods after they've been there for several releases.

    1. Re:Java is even less standard though! by Anonymous Coward · · Score: 0
      A good example is how they use: array.length to give you the number of elements in an array, but then if you use the ArrayList you use arraylist.size() to get the number of elements.

      Despite this and other oddities in Java, I'll NEVER go back to C and C++. C++ is an archaic mess that should be left in the computing stone age where it belongs.

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

  206. Experiences with exception safety in STL by Anonymous Coward · · Score: 0


    I'm curious about peoples' experiences with exception-safety in various STL implementations.

    If during some operation an STL function calls your code which then throws an exception, do STL implementations guarantee integrity of any data structures that might have been in an "in-between" state at the time the exception was thrown?

  207. RE: by Anonymous Coward · · Score: 0

    The only problem with STL and C++ in general esp. by judging from what I read on here is the lack of qualified programmers.

  208. Downside by NDSalerno · · Score: 1

    One downside of the C++ STL is that it is not Delphi's VCL.

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

  210. Re:Not all compilers support it, god-awful comp er by gkatsi · · Score: 1

    Not exactly the same thing, but I read recently on the boost mailing list that someone had created an extention to gcc that allowed him to 'instruct' the compiler to not emit these awful errors. So instead of a couple of pages of error messages that essentially tell you that you have not defined operator== (or something that trivial), you get a single message like "need to define operator== for class Foo when passing it to library Bar"

    It was very cool and people seemed to like it. Let's hope that the standards body considers something like it non-intrusive enough to include. Of course someone would have to actually write up the proposal, too. So it may remain a gcc-only feature, if it even appears in mainline gcc.

  211. Never hire a real man to do a woman's work by Anonymous Coward · · Score: 0
    Real Men write their own STL implementations from the ground up and use that, instead of any of the standard impementations.

    Real Men also choose to program in Perl, in order to ensure their job security, and then pose as if that makes them studly. In short, Real Men are morons.

    That's why more women should be working on software development projects.

  212. 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.
  213. Re:Why is inheriting from an STL class such a bad by Uncle_Al · · Score: 1

    what about:

    class myclass {
    typedef vector::iterator iterator;

    //whatever
    }

    should work rather nicely ;-)

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

  215. Re:hey! lay off Java by Anonymous Coward · · Score: 0

    cat>Hello.java
    import java.io.*;
    public class Hello {
    public static void main(String[] args) throws Exception {
    System.out.println("Hello");
    new BufferedReader(new InputStreamReader(System.in)).readLine();
    }
    }
    javac Hello.java
    java -cp . Hello
    Hello
    ^Z
    ps x|grep java
    coward 19341 0.7 1.9 170272 7548 pts/0 S 02:01 0:00 /usr/local/jdk1.3.1/bin/i386/native_threads/j ava -cp . Hello
    eight repetitions of former snipped due to lameness
    coward 19386 0.0 0.1 1364 452 pts/5 S 02:02 0:00 grep java

  216. C++ is a horrible language. by MeanGene · · Score: 1

    Wrote 25+ KLOC application in it - never again. If you want to use several libraries in your code (which you do, since reinventing the wheel is not in your job description and is boring), these libraries demand seemingly incompatible compiler flags. So, building all library variants - static/shared/repo/optimized becomes a major PITA.

    Then you want to migrate from Solaris to Linux, and you have to fiddle with the code again, because Linux versions of all libraries wouldn't compile with -frepo.

    1. Re:C++ is a horrible language. by Anonymous Coward · · Score: 0

      Don't worry, I was talking to your C++ compiler and it told me that it would never work with you again either because you're an idiot.

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

  217. 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
  218. 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
  219. Re:Not all compilers support it, god-awful comp er by bmoore · · Score: 1

    Believe it or not, eventually you do learn how to read them without much trouble.

    This is quite true. For whatever reason, my eyes very quickly bounced from "conversion from `_List_iterator" to "to non-scalar type `list".

    That basically tells me all I need to know, along with the line 109 of readply.cpp. Maybe it is just mental training, but the STL errors that g++ generates are workable messages. You just need to get used to finding the relevant information.

    Of course, I try to stay away from C++ anyway, and stick to C, but that's just personal preference for the most part. The real smart thing is to use the tool (language) that fits the problem best.

  220. 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
  221. Re:hey! lay off Java by norwoodites · · Score: 1

    The "eight repetitions of former snipped due to lameness" is not java's fault but Linux Threads fault.

    Get a real kernel.

  222. err, tabs aren't an issue by demian031 · · Score: 1

    i have used python in production environments since 1997, i use java for the most part right now. i have NEVER had a problem with tabs messing up the flow/ parsing of my code in python.

    some of your points are valid but the same can be said about assembler; a human can write better assembler than GCC.

    i guess it comes down to if you want to program to satisfy your ego by doing it 'old school' or if you want to get business functionality out the door. if you're writing device drivers and intensive number crunching then C/ C++ is your thing. but if you need to slap together an app to get it out the door and in front of users, Perl, Python, Java are great tools ...if you insist on C/ C++ you are doing a dis-service to your clients.

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

  223. 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));
  224. Re:hey! lay off Java by Anonymous Coward · · Score: 0

    ok. what was i thinking. 9 threads for helloworld is completely reasonable after all.

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

  227. Unreal.... by Kashif+Shaikh · · Score: 1

    For a person who plays Unreal, I've seen such statements now and then:) Only now, you've taught me thats its a STL template error. ooooo aaaahhh!

    1. Re:Unreal.... by SteamedHams · · Score: 1

      I agree that Unreal's error messages are larger than your average bible, but that doesn't point to STL

  228. Re:Not all compilers support it, god-awful comp er by abdulla · · Score: 1

    I see a lot of people are bitching about the template expansion and how incomprehensible it is, I agree (I've had my share of problems), but it comes down to the way the compiler displays this information, this can be solved easily if the compilers output could be made graphical in some way to aide interpretation, eg. branches of instantiation to show clearly the point of error and the path it leads down. On the other hand, I strongly disagree that templates in C++ are incomprehensible, that all comes down to the writer and the syntatic sugar, you can't blame the language when it is the writer who made it look awful. template const my_type returner( const my_type* const object ) { return *object; } I find that much more readable than writing an overloaded function for every single type that could be used.

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

  230. Re:Not all compilers support it, god-awful comp er by Anonymous Coward · · Score: 0

    > Take List in Java, for example. You have the code of List just once even if you have several lists, one with apples and the other with bananas.

    And, in Java, you can have a list containing both apples and bananas, even when only apples was intended. The compiler doesn't help - you have to write runtime type checking code, or wrap that generic List within a type-checking outer class; voila', templates!

    Now you know why generics are being added to Java.

  231. Re:hey! lay off Java by elphkotm · · Score: 1

    Suprise! Java wasn't engineered for "Hello World" applications. You're forgetting that there's a VM and a compiler loaded there. Please show us the size of your GCC, and the differences between the Java bytecode and the native binary.

    --

    <Amanda`> I just went out to the parking lot in my bathrobe to exchange warez CDs.
  232. 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 PissingInTheWind · · Score: 1
      I agree with what you say, I'm just curious on one point.

      [Perl] has also graphically failed several times in the telecoms world that I'm aware of.

      I'd like to learn more about that, got any pointers?

      thanks

      --

      A message from the system administrator: 'I've upped my priority. Now up yours.'
    2. 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."
    3. Re:Perl is like Duct Tape by PissingInTheWind · · Score: 1
      Mmm. You know I work in telecom, and I think I might have an idea of who you're talking about, or what kind of company it is. Since you and I are both canadians, we know that the telco field around here is pretty small ;-)

      anyway, have fun.

      --

      A message from the system administrator: 'I've upped my priority. Now up yours.'
  233. 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++);
    }

  234. Re:Debugging ...Who modded this thread down? by MeddlesomeKids · · Score: 1

    I think what is needed is a new language that will put compile-time and run-time code on equal footing. It would be great if they had the same syntax. Lisp has the same syntax for macros as it has for any of its code. If your project depends upon the genericity and data collection that STL provides then you probably would be better served my Lisp (IMHO). Obviously, if you are at a business where C++ is required then Lisp may not be an option for you. But if you have the freedom to make language choices, check it out. http://www.alu.org

  235. Not a standard reference implementation by thammoud · · Score: 0

    The biggest issue with any C++ 'standard' library, is that every compiler vendor has to implement the standard. Leading to incompatibilties and wasted resources.

    What C++ needs is something like Java. a standard reference implementation that all licensed compiler vendors can resue. If all Java compiler vendors had to rewrite the standard Java libraries, it will take thousands of man hours and introduce all sort of bugs. Atleast bugs in the current Java implementation are isolated and reasonably well addressed.

    I am glad that we switched away from C++ to Java for our server implementations. Will never look back.

    1. 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...
  236. "slap together" code -- what an argument by IBitOBear · · Score: 1

    While I often do "slap togehter" code when I know I am going to use it onece and throw it away. Or when I am prototyping it...

    It is intrinsicly evil to *DELIVER* "slap together" code.

    The median case, where you are safely within bounds is all well and good, but if you deliver actual product that has to run dangling-anatomy-to-the-wall for months you had better not be slapping anything.

    [begin steadly increasing rant/troll]

    I do not do things "old school" for ego's sake. What a pitious reason to do anything. I do things 'carefully' and 'with the correct tool for each job' because I can not STAND to have to go back and do the same job more than once. My opinion might differ if I were "a consultant" where my big dime came from return visits to do maintenance. Then again, probably not, doing inferior work to keep a job alive is dishonest and goes against my work-ethic. I consider my code like furnature. I make a chair I am done with that chair. Going back and re-making that chair when I could be making coffie table or a new and better chair would be stupid, boring, and wasteful. I also {GASP} reuse my own code in later projects because, having made a chair it would be a shame if it was only sat uppon one time.

    The web and the "e-economy" has gifted us with a lot of truely sub-standard programmers. Part of this is the inherent nature of CGI. (It's one invocation one action nature allows some truely horrific code to "work well enough".) If every invocation is atomic and it sometimes fails, the user hits reload. If their dataset always fails then that user doesn't come back, usually without complaint.

    That screw-the-boundry-case mentality is real business to some folks, and those reloads and abandons actually cost tiny amounts of money, not so tiny when it is considered en-mass.

    To your particular bragg: I am very happy for you that you have never had a white-space error mess up your code. Hurray for you. [Not that I actually beleive you. Perhaps you have never had a "tab vs space" mess you up, but when you hold that statement up as a "glittering generality" (= look it up, or ask your lit professor 8-) you will be evaluated in the general case...] Pitty the poor bastard that has to deal with it (the source code) later, especially if gets passed to him via email or MS-Office.

    I am sure in my soul that someone somewhere has made the same claim of "never having had a problem" with respect to his RPG code too. It still doesn't make whitespace a valid control structure that a sane person would want to use. "It is perfectly safe as long as (your condition here)" isn't a good argument for desireability, only acceptable necessity, and it WASN'T NECESSARY.

    Was saving the one keystroke (the close brace) per conditional block really that valuable compared to having to mess around with all the "special" Python-friendly editors? How about the number of times someone has has accidently mis-indented a statement?

    Was that value?
    Was the wasted time spent to the greater good?
    Is the counting-spaces durring each compile an asset?

    Computers are damn fast these days so most people don't even sneeze over wasted cycles. It's sad. One wonders how much faster and better any given program might be if the programmers still thought of one machine instruction cycle as a valuable resource.

    Game programmers understand, engineers understand, batch-process workers (banks etc) understand.

    Anybody who has ever had to maintain code understands.

    But I guess we are all wrong... your five whole glorious years of *occasional* Python use has enlightened us all to the folly of our conservitive attitudes...

    Meanwhile you keep slapping together those deliverables and we will bask in your magnificence.

    8-)

    --
    Innocent people shouldn't be forced to pay for inferior software development.
    --"Code Complete" Microsoft Press
    1. Re:"slap together" code -- what an argument by LordBrutish · · Score: 1

      > Was saving the one keystroke (the close brace) per conditional block really that valuable compared to
      > having to mess around with all the "special" Python-friendly editors? How about the number of
      > times someone has has accidently mis-indented a statement?

      You mean special editors like vi or emacs? :-)

      Seriously, I have programmed in Python nearly full-time for the past two years. I will not lie -- I *have* occasionally had problems with indentation/formatting of blocks ("occasionally" = perhaps 10 times in 2 years). But the fact of the matter is, the productivity gains I've experienced with Python have outweighed this trivial inconvenience by orders of magnitude. Like most programmers who actually give Python a try, the whitespace thing bothered me for about 20 minutes, and then it was "oh, I just indent my code the way I normally do. How kind of them to create a parser smart enough to figure out where I want to put blocks based on my own code formatting habits, and not force me to use some annoying bounding punctuation!"

    2. Re:"slap together" code -- what an argument by cduffy · · Score: 1

      I use Python frequently, as a prototyping languge, as a language for administration tools, as a language for other miscellany that should be simple, maintainable and correct; though not for anything run by an end-user, or which batch data is run through (those things I leave to languages with strong typing).

      That said, though, Python's whitespace control structure is well-designed and well-implemented. Simply put, it Does The Right Thing, consistantly and without fail; a failure in the whitespace would be as user-driven as braces being placed wrongly. Python figures out the tabs-versus-spaces thing correctly every time (whether I'm doing tab-as-four-spaces or tab-as-eight), or refuses to parse the code if it can't. Further, the improved productivity based on its language features (ie. the best introspection of any language I've ever used, anywhere) more than makes up for any (nonexistant!) losses due to whitespace-related issues.

      Further, as the premier Python-friendly editor is emacs, I hardly think the time "messing around with" the editor I've used for years has been any variety of an issue.

      I tend to use the right language for the job -- C, Java, Python, Scheme, whatever it may be. Be nice to Python. When the problem space is appropriate, Python can be the best friend you've got.

  237. 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
  238. Re:Not all compilers support it, god-awful comp er by Heinrich · · Score: 1
    I can cast to (void *) in C++ just as well as I can in Java.

    Sure, you can do this. But do you really want to leave the type system even for a list of bananas or apples? One important reason (among many others) to use templates in C++ is to survive the absence of a general base class without giving up type safety.

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

  240. Re:Not all compilers support it, god-awful comp er by Heinrich · · Score: 1
    Now you know why generics are being added to Java.

    This was not a discussion whether we want to use templates or not but about how expensive they are. Templates cause more code to be generated for several instances of lists than Java where we have just one piece of code handling all lists. That the lists of Java do not allow you to restrict a particular instance to bananas is nothing new. Nor is the discussion about OO techniques vs templates / generics something new. That discussion was already started long ago with the paper ``Genericity vs Inheritance'', SIGPLAN Notices, vol 21, no 11, November 1986, by Bertrand Meyer.

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

  242. STL creator Stepanov's opinion by Anonymous Coward · · Score: 0

    This interview with Alexandre Stepenov is pretty amusing. He apparently calls OO programming "a big hoax". He also states "quite clearly that Bjarne [Stroustrup] is the preeminent language designer of my generation."
    A very interesting read.

  243. a couple of pointers by Anonymous Coward · · Score: 1, Informative

    http://www.slac.stanford.edu/BFROOT/www/Computing/ RWmigration

    http://lnxatd01.cern.ch/Atlas/DaqSoft/rw2stl

    Enjoy!

  244. Re:Why is inheriting from an STL class such a bad by Anonymous Coward · · Score: 0

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

    No, this is not a bug. There won't be any bugs if you do it correctly. Just make sure that the derived class doesn't need a destructor, and don't use any virtual functions, and you'll be totally safe.

    It's not "bad design". It will work just fine (and safely) if you know what you're doing.

    It doesn't make any sense to criticize the design of a working class just because someone *might* add some code to it in the future that *might* cause it to break. If that was a valid criticism, then every single class in the world would be bad design.

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

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

  247. It's a different way to program by Steve+Heller · · Score: 1

    I agree with some of the other comments on this thread. The STL can be hard to learn, the error messages generally stink (but that's really the compilers rather than the library), and it's easy to get yourself in trouble because of the complete lack of error checking. I also agree that people who only learn how to write C++ programs with the STL and don't know how to implement any of their own data structures or algorithms are going to be pretty useless when they get out into the real world.

    All that said, however, I believe it has a very important role in allowing highly efficient programs without locking you into one particular data structure or algorithm. I just think it should be kept inside user-friendly classes rather than put in the main program, if you have a choice in the matter (and you almost always do).

    Before I would teach someone the STL, though, I would make sure that he understood the basics of C++, like variables, classes, inheritance, and polymorphism. Then he would be able to use the STL and a productive way without being overly dependent on it. After all, you can't expect every algorithm for data structure you ever need to be provided as part of a standard library.

    By the way, if anyone is looking for a good C++ programmer, you may want to look here.

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

  249. PushBack Problem by Anonymous Coward · · Score: 0

    Has anyone faced problems with queue push_back() function in a multi threaded program, multi processor box?

  250. Queue PushBack Problem by Anonymous Coward · · Score: 0

    Has anyone faced problems with queue push_back() function in a multi threaded program, multi processor box?

    I'm running out of memory...

  251. Re:Not all compilers support it, god-awful comp er by David+Greene · · Score: 1
    To say that the preprocessor is equivalent to the C++ template engine is...well...wrong. :) There's a lot more to templates than type-safe inline functions (which are nice, to be sure).

    The great power of the template engine is specialization and pattern matching. This allows compile-time functional programming, known as template metaprogramming. Metaprogramming provides all sorts of cool possibilities, including program generation, type-safe, compiler-aware conditional compilation, blazingly fast numerical computation and embedded domain-specific languages. For examples of the latter two, check out Blitz++ and Spirit, respectively.

    --

  252. Re:Performance & size tests, c, gcc & stlp by Anonymous Coward · · Score: 0

    First of all, you have to make sure you turn off syncing with stdio. This prevents you from mixing iostreams toghether with printf/scanf but it speeds up things a lot.

    Second, gcc's c++ libraries threw away their internal buffering becuase noone stepped up to maintain it. So, it's not exactly the language, but still there's room for improvement.

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

  254. Re:Not all compilers support it, god-awful comp er by jgp · · Score: 1

    Or you assigned your apples:

    std::list::const_iterator

    to non-scalar oranges:

    `std::list'

  255. Re:Not all compilers support it, god-awful comp er by scotch · · Score: 1
    To say that the preprocessor is equivalent to the C++ template engine is...well...wrong.

    Which is, of course, why I didn't say it.

    --
    XML causes global warming.
  256. My Biggest Gripe About STL by Anonymous Coward · · Score: 0

    While, in general I like the STL and I use it often there is one design flaw that makes it unnessasarily more difficult to use. An STL container iterator can only be defined if you have a complete definition for the object which you wish to contain. This means you need to create an extra set layer of classes if you want an class to contain an iterator to itself.

  257. It isnt objective C at all.... by Anonymous Coward · · Score: 0

    you want a real programming language, use Objective C on Mac OS X. Much much better than than c++. Trust me.

    It has much more power than Java. It has all of C's speed. It is much more object oriented than c++ will ever be.

    Objective C!

  258. 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!
  259. STL Error Translator Here! by d-rock · · Score: 1

    http://www.bdsoft.com/tools/stlfilt.html
    Works pretty well, available for lots of compilers!
    The above example boils down to:

    BD Software STL Message Decryptor Release .99 for g++ (4/11/2002)
    readply.cpp(109): conversion from `iter' to non-scalar type `list' requested

    --
    Don't Panic...
  260. Re:Not all compilers support it, god-awful comp er by David+Greene · · Score: 1

    Oops, you're right. I missed "some of" in your original message. My apologies. It's been a late night of hacking. :)

    --

  261. Problems inheriting from STL? by Anonymous Coward · · Score: 0

    You should never inherit from a STL container? I've read a whole bunch of C++ tips and guidelines, but I've never seen that one before. Sure, you've got to be careful about the virtual destructor thing -- but that's true for all classes. You say that warning like you've had some horrible experience with it. But I've done it a few times, and it seemed to work ok. I read this whole thread, but I still don't see why the STL classes are worse base classes than other classes. What's the special case with STL?

  262. Re:Not all compilers support it, god-awful comp er by leviramsey · · Score: 1

    I especially like this example:

    #include <iostream.h>
    #include <stdlib.h>

    template <int nb>
    void SingVerse() {
    cout << nb << " bottles of beer on the wall;\n"
    << nb << " bottles of beer.\n"
    << "Take one down, pass it around.\n"
    << nb-1 << " bottles of beer on the wall\n";
    }

    int main(int argc, char** argv) {
    for (int i=99; i>0; i++) {
    SingVerse<i>();
    }

    exit(EXIT_SUCCESS);
    }

    Yeah, I know that was kind of pointless...

  263. perfect timing by fifthcent · · Score: 1

    I'm reading this immediately after finishing my final CS2 project, where I was required to use STL containers, and also supply a write-up explaining why I chose such containers.

    The assignment itself was a bit absurd (weird, not hard) though... emulating pine on an extremely basic level, ie not really going online, not using ctrl commands, etc etc.

    Oh well, at least is was satisfying to have it finished and working.

    --
    my $.05
  264. Re:Not all compilers support it, god-awful comp er by David+Greene · · Score: 1
    This won't work. You're trying to use compile-time evaluation (int template argument) at run-time. You need a compile-time for loop. Check Generative Programming for an example. A compile-time loop will give you programmer-controlled loop unrolling. I suppose you could say this is the C++ equivalent of Duff's Device. :)

    <pendant>
    Always use standard C++ headers:

    #include <iostream>
    #include <cstdlib>

    </pendant>

    --

  265. Why? by Anonymous Coward · · Score: 0

    I don't get it. I don't have a destructor in my subclass, so what's the harm? (I didn't use virtual, I just kept it nice and simple.) Please let me know what I did that's not valid. It's working ok, but now I am worried!!!

    -- D.S.

    1. Re:Why? by Anonymous Coward · · Score: 0

      If you didn't add any member data to the subclass that requires explicit destruction then you have nothing to worry about. Since you didn't add a destructor to your subclass this would seem to be the case.

      You're class will work fine (as you've already said it does).

      No worries mate!

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

  267. Re:hey! lay off Java by Anonymous Coward · · Score: 0

    Wow - I really hope you don't actually consider Perl to be a suitable alternative to Java, it is a scripting language for crying out loud (and an incredibly ugly one IMHO), I can't believe that whatever magic fairy-dust they plan to sprinkle on Perl6 will change this much.

    I, too, have a hard time believe Perl6's objects will beat Java's, but I really haven't been paying much attention.

    Calling Perl a "scripting language" just proves you don't know what the fuck you're talking about, though. Perl is a compiled language. It's just (generally) compiled at runtime instead of ahead of time.

    There are plenty of reasons to dislike perl, but resorting to lame attacks like calling it a "scripting language" (as though that matters) proves that you don't really pay attention to many languages besides your beloved Java.

  268. 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.
    1. Re:Heh by bn557 · · Score: 1

      I've done one fix that took me from 75 errors to 0. one semi colon. In C++ and not Java.

      P

      --
      Humans are slow, innaccurate, and brilliant; computers are fast, acurrate, and dumb; together they are unbeatable
  269. 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...

  270. Re:Binary incompatibility and buggy implementation by epine · · Score: 1


    Binary incompatibility is a well known and well documented problem. Given your attitude, you will be better served by a language which specializes in late bindings. Late binding is the patron saint for wading into something without first scouting the terrain.

    There is now a standard ABI for C++, but it is not yet widely supported. Too many vendors don't regard this as a priority.

    The reason that gcc 3 failed is that it is attempting to support the standard ABI. gcc 3 had to change in order to do so.

    I'm sure you'll be happy to know that in the case of gcc it was the cure that killed you. OTOH, avoiding VC6 like the plague is not such a bad idea.

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

  272. Downsides and benifits. by j_kenpo · · Score: 1

    Ive come across a few issues using STL. Although the benifits more than outweigh the disadvantages. Biggest one is compatibility with vendors, mostly with VC6. Cygwin and G++ seems to work alright, with one exception using the size() function and the capacity() function with vectors, although I cant remember what exactly it was off the top of my head. Some performance loss has been experienced, but only slightly in my case, and code seems to compile a little large for simple programs. And probally the biggest annoyance Ive come across with containers is declaring them. Multiple declarations of container variables across functions will get annoying, I dont think Ive ever used the typedef statement so much until I started working with STL. Other than really simple annoyances, the STL is a great time saver with the containers it provides, and the iterators make working with pointers a breeze. I havnt so much been very impressed with its Algorithms, but then again I havnt really come across much of a need for them either, although there are some good ones. Other than vendor specific issues and minor annoyances, I dont really have anything real bad to say about the STl.

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

  274. 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.
  275. 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?

  276. *Rouge* Wave? by jdfox · · Score: 2


    That must be the San Francisco-based subsidiary of Rogue Wave, right? :-)

  277. Some downsides by Anonymous Coward · · Score: 1, Interesting

    We used STL in a large project and ended up rewriting all parts that used STL because of two problems: One is that a lot of STL implementations - specifically the one that comes with g++ aren't thread safe. Supposedly stlport is thread-safe, but then their iostreams library isn't (but g++'s iostream library is - so you _can_ get it to work). Secondly, it is a pain to debug. Write your own template-based lists, hash-tables etc. and slash your time spent debugging by an order of magnitude. If you use STL and you're like me, most of your bugs will be related to data-structures that you use STL for, and that is exactly when you don't want to wade through the complexities of your STL implementation.

    Just my 2 cents.

  278. GCC/C++ is slow, especially STL code by r6144 · · Score: 1

    Probably because it does not support precompiled headers.

  279. Re:Why is inheriting from an STL class such a bad by licate · · Score: 1

    Writing STL-style iterators is, in my opinion, an enormous pain in the ass, involving lots of tedious coding.

    ... or half an hour's worth of less tedious coding using the Boost iterator adaptor library?

  280. Things missing in STL by quench · · Score: 1

    here's my short list of STL problems:
    - decent pointer support missing (who wants to copy objects, large or small) -> usually ends up
    extending the STL with home grown untested extensions
    - missing single linked list, double linked list in std::list is an overkill, std::vector is too little as a container
    - on the other side, who really needs a std::deque

    q.

  281. Butchery of "Effective STL" by Myers by fnj · · Score: 1

    Sorry to put it this way, but you have butchered/misunderstood what Myers says.

    Actually, I bet you've been bit by HTML syntax, which renders plaintext invisible. Here's to proofreading :-)

    Neither Myers, nor any other proficient C++ programmer, would claim that vector is an ill-conceived specialization and not a container. What he says is that vectorbool is an ill-conceived specialization and not a container.

    vector is a well engineered general container, and an excellent replacement for C arrays in most cases (C arrays are Bad Things in general). vectorbool is a specialization of conceived in such a way that it doesn't even behave like a vector. It is bad.

    1. 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));
  282. Re:Not all compilers support it, god-awful comp er by Anonymous Coward · · Score: 0

    I can't see why the STL errors would be any reason for any grif, makes all perfect sense to me! ;-)
    Mind you I use a BrainFuck precompiler since I refuse to program in anything less than the one true language one should use...

    disclaimer: I'm just trying to be a bit funny, ok?

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

  284. Re:Debugging is the downside - LISP by Anonymous Coward · · Score: 0

    The new language you're looking for is lisp/scheme
    e.g. Common Lisp macros have supported a clean form of generic programming forever.
    Of course using dynamic typing helps too.

  285. VC++ STL experience by SailFly · · Score: 1

    I found STL very useful. I would suggest these things first:

    1) Take the time to learn it (write some 'toy' programs, and experiement. I took about a week).

    2) Get a good book, and read it. I looked on amazon for the user discussions, then bough at bookpool.com to save a few $$$. I use the book "STL Programming from the Ground Up" by Herbert Schildt.

    3) Research the known bugs for your implementation of STL. VC++ has several, one that stumped me was the use of my own sort function (funtor) in sorting a list of elements. As I recall, VC++ will not sort more than 16 elements (VC++ 6.0 SP5), so we had to call an internal reference generated by VC++ to make it work.

    4) If you're using VC++, I suggest you take a look at sellsbothers.com for their tips. I even found a tip on which byte to change in msdev.exe to increase the thread priority of the compiler, to make it compile a bit faster.

    5) Talk with the other developers at your work place (or school). They may have insights and feedback too. Also, consider if other people will be using this code, or if it's just you. Sometimes other programmers don't want to learn new things, and your choice of using STL might create a larger problem (social)

    Anyway, good luck with it!

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

  288. say no to new and delete by rsdavis9 · · Score: 1

    The thing I like the most about stl is: I have written 2 large(moderate) projects in stl and I have not used a single new or delete. Therefore there is no memory leaks and associated clean-up work. My destructors are almost always emtpy and my constructors are usually the simple initialization type. Also I have very few pointers. At first I tried to code w/o any pointers but I found cases where I couldn't use a reference and had to use a ptr. For example if a particular variable is optionally valid a ptr is much better(NULL or not NULL). Also any collection of references doesn't compile(correct me if I am wrong).

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

  290. std::auto_ptr by Anonymous Coward · · Score: 0

    IMHO the purpose of std::auto_ptr is not smart-pointing but to provide:

    void subroutine( int n_dynamic_size )
    {
    ...
    float size_dependant_array[ n_dynamic_size ];
    ...
    /* No delete[] since automatically done by compiler */
    }

    that some compilers such gcc allow. And it is sooo comfortable!... but... sooo un-portable!. The correct code would be:

    void subroutine( int n_dynamic_size )
    {
    ...
    float * size_dependant_array=
    new float[ n_dynamic_size ];
    ...
    delete [] size_dependant_array;
    }

    and the std::auto_ptr should be something like this:

    void subroutine( int n_dynamic_size )
    {
    ...
    std::auto_ptr size_dependant_array=
    new float[ n_dynamic_size ];
    ...
    /* No delete[] since automatically done by auto_ptr */
    }

    OK, an smart pointer would do the job but, again IMHO, with a small overhead respect to std::auto_ptr.

  291. Error Messages by Nepre · · Score: 1
    IMHO, the worst problem with STL is the compiler warnings and error messages. It's very rare that you write code that compiles the first time. When you do make a mistake, it's very difficult to figure out what went wrong. For example:

    c:\program files\microsoft visual studio\vc98\include\functional(86) : error C2784: 'bool __cdecl std::operator &,const class std::multiset &)' : could not deduce template argument for 'const class std::multiset &' from 'const class S'

    A while back I came across a Perl script that translated these error messages into something readable, but it seems to be that the compiler should do this for you. Maybe gcc is better...
    1. Re:Error Messages by Anonymous Coward · · Score: 0

      like any error in c or c++ you deal with the VERY FIRST error. to illustrate my point just put an extra ';' in any code anywhere. if you start in the middle or the end of the error messages you will never find the "real" error which caused the whole mess. a lot of it is just seeing more error messages. as you see more you will easily identify your errors. use objects. compile more often. you'll catch a lot of the "stupid" errors.

  292. Re:Not all compilers support it, god-awful comp er by Heinrich · · Score: 1
    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.

    This is simply nonsense. Java does not enforce it. It is even not allowed in Java because Java has a safe type system unlike C++. There exist no such thing like a void * in Java nor is it possible to cast something to it. The base class Object is something completely different in Java as you do not lose type safety using it.

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

  294. Why STL/C++ isn't a good idea by ratboy666 · · Score: 1

    Making templates to speed up code seems like a
    marvelous thing. Of course, if you REALLY need
    this for performance, you are probably targetting
    embedded systems, where the code bloat and testing
    become prohibitive. So, what's the real difference
    between C++/STL and C/M4? Not a hell of a lot,
    really (really, truly, equivalent "type checking"
    can be done in M4). The syntax is just as ugly,
    and the tools are worse.

    Of course, templates (STL) are ANTI-object
    oriented programming. No factoring, and I must
    regenerate code. Wait a minute, if the language
    actually supported types as objects, then it
    wouldn't matter, the OOP system would take care
    of this for me... and it would, except that
    C++ programmers (generally) seem far too
    concerned about "performance".

    Another strike against C++ is the SIZE of the
    language. A good programming language reference
    manual should be expressible in 12 to 20 pages.
    That's it. Anything more cannot be reasonably
    used. C, Smalltalk, Eiffel, good. C++, ADA,
    Perl, bad. If I can't read it, I can't make
    use of it, and its probably easier to rewrite.

    If you like C and want OOP, use Objective C.
    If you like C and want templates/STL, use M4.

    And -- your experience with M4 can be leveraged.
    Get this concept: learning M4 (TRAC or one
    of the general macro/string languages) leverages
    BETWEEN languages. I recommend M4, not because
    its better, but because its everywhere. And, you
    can use it with C, Assembler, C++, etc.

    Ratboy.

    --
    Just another "Cubible(sic) Joe" 2 17 3061
  295. 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!
  296. Regarding your comments on STL by NewOldGuy · · Score: 1
    Regarding STL debugging, you said: If something's not compiling that you think should, you end up wading through the mile-long error messages.

    With a little practice it's easy. Look at the beginning of the error message and maybe the end. Never the middle. 90% of the time it's invalid parameters (template type vs. parameter type). Perhaps you forgot to add std:: to less in

    std::map<myClass1,myClass2,std::less<myClass 1> > myMap;
    That one took about five minutes to find because the compile error showed up in something like xtree.cpp. It took a few minutes to discover that it was the map declaration causing the problem. Once you 'grok' the essence of STL philosophy, it's really not any harder than that. My most common runtime error is dtor'd objects in an STL container - so far always my own fault, not the library's.

    If it does compile but doesn't work right, you're going to find yourself in the debugger trying to step through some of that crazy obscure STL C++ code

    I say don't ever step through that stuff unless you're trying to learn how it works. Just look at the parameters to the calls and then look at the results. Lots of times I'll change e.g.

    std::map<int,std::string,std::less<int> >::iterator it;
    for(it=mapMine.begin();it!=mapMine.end();it++ ) {
    ProcessMine(it->first,it->second);
    }

    to something like this:

    for(it=...blahblahblah {
    pair<int,std::string> p=*it; // I'd avoid the pair and go directly to the int and string
    int i=p.first;
    std::string s=p.second;
    ProcessMine(i,s);
    }

    for the simple reason that I can set a breakpoint on the ProcessMine(...) call and see what the iterator is referencing. I put things back when I've fixed the bug. But I do not go mucking around in the STL code itself other than to learn more about how it works. The point is, it does work as long as it's called properly (except when it doesn't, which hasn't happend to me that I know of).

  297. Depends which implementation of STL by Anonymous Coward · · Score: 0

    normally the one's you pay for are higher in quality and have more features (such as hashed maps, etc.)

  298. Re:Downsides to Deep Anal by Anonymous Coward · · Score: 0

    cock munch

  299. Common Lisp does every last thing you mention by NewOldGuy · · Score: 1

    I'm looking forward to somebody starting over some day and coming up with a language that supports generic programming as well as C++, but which doesn't have the terrible syntax of C++ templates. It must be possible.

    Yup. Common Lisp does all that plus everything you reference below... To keep this short(er), search slashdot for Kent Pitman and read his two-postings interview about Lisp. Go to www.paulgraham.com and download his free book On Lisp. Download GCL, CLISP, CMUCL, or Xanalys' or Franz's personal editions and work through every example in Paul's book, typing it in running it until you understand.

    Common Lisp compiles to very fast code, Xanalys offers unlimited runtime distributions and, I've been told, very flexible support for what's included in the runtime.

    On Lisp changed my programming worldview. I've been programming STL for years but now see large parts of it as an attempt to bring a small part of Lisp to C++. STL succeeds in that, and I do enjoy STL programming. However, why not just use Common Lisp which has all that and much, much more?

    ...templates can can be used to create programs that run at compile time to do some very clever optimizations

    Lisp does that...

    But the code to make this stuff happen is ATROCIOUS!

    Not in Common Lisp, it's not. Define a macro instead of a function and selectively add backquotes and commas. Otherwise, it's plain old normal CL.

    I think what is needed is a new language that will put compile-time and run-time code on equal footing. It would be great if they had the same syntax. ...

    Lisp does that.

    ...say something Lisp-like...

    You mention Lisp but you don't mention that Lisp does everything you're asking for. Hope I'm not boring you, and there's probably someone else who didn't know Lisp does all this. In addition, I know that Xanalys in particular (as probably do all the others, with whom I have less direct experience) makes calling OS functions nearly trivial. I've not yet tried callback functions under Windows. Your mileage may vary. I am not associated with Xanalys although I did just buy their Lisp because of the unlimited runtime distribution. I learned Lisp using GCL under Linux. I am not a lawyer. I ....

    Sounds to me like it's time for some new language stud to come and save us.

    Sound to me like it's time to pay attention to the old language studs. Seriously, with GPL implementation, commercial implementations with unlimited runtime distributions, etc., very fast compiled code.... it seems to me that unless you:

    • are doing real-time apps where garbage collection is unacceptable (and you're unable to write Lisp code that avoids the GC)
    • really need to pay attention to the final object code's size (critically need - as noted before, STL doesn't cause template bloat in non-debug compiles).
    • hmmmmm I'm running out of reasons here
    • Human factors - "nobody uses Lisp", "we'd never find programmers", "all those parenthesis"


    Note: modern editors make the parenthesis comfortable. They are the key to making Lisp extensible because anything following an open parenthesis is a function to be called. Define a function, you just added new syntax to Lisp. You can redefine existing functions, including those in the base package such as addition:
    (defun + (* a b))
    and addition is broken everywhere. Lisp is a power tool and should be kept away from children. Use it if you really need to build something incredible.

    What other reasons are there not to use Lisp? Lisp has had the features you named as important. Lisp has had them for years. And, speaking as one who has experience with STL, you simply don't need an STL in Lisp. Lisp is truly a giant STL. I don't have to define and name all the miscellaneous little structures I need, I just construct and use them on the fly. Not to mention closures, functions as first-class objects, lambda's (i.e. unnamed functions defined even in parameter lists), macros, run-time typing... the read-eval-print loop for debugging, the ability to replace a function in the middle of a running system with no giant compile/link... geeze Louise it's phenomenal. All those things combined seem to obviate the need for 98% of the things I use classes for in C++/STL. I'll know more after I build something really big in Lisp and have a lot of people using it. I'm working on that...

    I enjoy C++ and STL a lot. I'm really looking forward to a lot more finger time with Common Lisp. Don't want to give either one up. But my sense at the moment is that Lisp is by far the more powerful environment. It certainly does everything you mention in your post.

  300. My comments on STL by proxima+centauri+(W) · · Score: 1

    My comments are with the VC6 version of the STL and do not necessarely apply with another compiler.

    When I first started using STL, I first hated the fact that everything had an underscore (argh!). Second thing that pissed me off was the nomenclature of the methods. For instance, with the stl vector, what did I expect std::vector::empty() to do? I expected it to empty the vector. What does this actually do? It tells you whether the vector is empty or not. Why not use a method called IsEmpty() ? or is_empty() ;-).

    After this first bad encounter, I decided to give it a shot and started using it extensively whenever I had the occasion. At first, mainly for strings and vectors. I found the iterators particularly fun to use. And now I would never go back to using char * or arrays unless I really have to. Mainly, I love the fact that everything a casual C++ programmer ever wanted IS in the STL, all these data structures you learned in school are integrated AND templatized! The only thing that is not explicitely included are trees unfortunately :-(. And yes, I know a std::map uses a binary tree structure.

    After using the STL on projects, I found 2 major irritating things:

    1) When you have a syntax error, the compiler lets you know by filling the screen with the function signature and it can be hell to decipher if you're not used to it. And with VC, if you use vectors without a #pragma warning ( disable : 4786 ), the warning the compiler gives you takes 10 lines.

    2) Some STL classes do not tranfert good between an application and objects in a DLL. Mainly cause some variables are on the stack of the DLL and cannot be shared with the main application. I think this is a M$ implementation bug specific, but anyway, it can be a pain in the ass to find a solution. usually, you have to use good old arrays and structs to transfert data between the DLL and the main app.

    Other than that, after the learning curve is flattened, STL is a great productive tool.

    proxima centauri, closest star to our sun!

  301. Re:hey! lay off Java by Anonymous Coward · · Score: 0

    you don't design neither VM nor language to create a "hello world"-program

  302. Re:C++ and dynamic libraries don't mix well by 21mhz · · Score: 1

    "DLL" can pretty much be extended to "dynamic libraries", and STL reflects the general failure of C++ in this respect. C++ was simply designed without the notion that some parts of a program can be reused in the binary form. This resulted in the ABI hell and bloat problems. The strict mapping of source code to binary code, identifier names to linker symbol names, that was essential for C, has been eroded in C++, and no viable remedy has been established as of yet.

    --
    My exception safety is -fno-exceptions.
  303. In other terms by 21mhz · · Score: 1

    After I sawed off my legs, I still make it fine with crutches and prosthetics.

    --
    My exception safety is -fno-exceptions.
  304. ATL by 21mhz · · Score: 1

    ATL COM is built entirely on templates (for better or worse, although their primary objective was reduced code size for ActiveX components- templates where largely responsible for this).

    Wrong. Their primary objective was automated generation of boilerplate code for COM objects.
    For this, I consider templates rather good.

    --
    My exception safety is -fno-exceptions.
    1. Re:ATL by HopeOS · · Score: 1

      This is a really minor nitpick, but whatever.

      After re-reading my notes, some older articles by Don Box, and the preface to Professional ATL COM programming, I am inclined to disagree with you. The COM programming environment was not lacking for boilerplate- MFC already provided all this and more, but only in an application framework. Meanwhile, historically, Microsoft was pushing the idea of ActiveX controls which could be downloaded quickly and conveniently from the web. The requested size was on the order of 5 to 15k, a ridiculous demand for an MFC application. In order to pull this off, it was necessary to strip everything, including a large portion of the C runtime library. The designers implemented a stripped-down static runtime to handle general C memory management, they disabled exceptions by default, and employed templates for tight, minimalist implementations of what we would both agree amounts to boilerplate code.

      The primary objective was very specifically to make ActiveX controls which would further cement the dominance of IE over Netscape. This is evidenced by the facts that 1) the first objects outside of "simple" objects that could be instantiated from ATL were in fact ActiveX controls, 2) the testing environments for ATL objects centered around full ActiveX controls and their test containers and were largely uninteresting for anything else, 3) the recommended build targets were geared for minimum size and minimum dependency - usually mutually exclusive but both requirements for web deployment, 4) great effort was taken to completely circumvent using the CRT including generating custom winMainCRTStartup code for ATL projects, and 5) until ATL version 2.1, there was barely even a sufficient IDE in MSDev to code in ATL. The only people using it in earnest were Microsoft developers themselves- for the implementation of ActiveX controls.

      Follow the money. Microsoft did not write template code because it was a Good Idea; they wrote template code because it made their code small, download fast, enhance the browsing experience, and further push Netscape off the map. Of course, this is all academic now.

      -Hope

  305. Ruby evangelism by cyphage · · Score: 0

    I realise the question is about the STL, but a lot of discussion has arisen about the failings of C++. I started on C, then Java, then C++, then Perl, M68000 ASM, PHP, blah blah. My favourite of the lot is Ruby. Ruby (unlike Java) has everything as an Object. It supports closures (much neater than function pointers) and has a clean syntax. It adheres to both Least Surprise and DWIM. Generic programming is default behaviour, design patterns can generally be encapsulated in a class and 'mixed-in' rather than requiring code everywhere. mod_ruby exists for Web applications, while Tk, GTK+ and (experimental) Qt bindings exist for GUIs. MySQL and PostgreSQL APIs are available. If you need low-level access or super-speed, C extensions can be written. There are no limits in Ruby - most notably very little distinction between compile time and run time. Ruby is more popular than Python in Japan, I'm told... check it out. There's a free book online.

  306. Python blocks *ARE* explicitly delimited by IBitOBear · · Score: 1
    And what is this crap about not having an explicit begin and end delimiters/statements for blocks of code being a "good thing"?

    The funniest thing is that there *IS* a block start character. The colon ":" starts the block. There is also an explicit end of block (the blank line or change of indent). The fundamental truth: Both the colon and the white space *ARE* *EXPLICIT*. See explicit definition 3, if the system can tell where the block ends... And if it just guesses... Or if you put in in wrong...

    The block delimits are "less robust" and easy to fsck up but not explicit == implicit (follow the link 8-) either that or Python is a deliberate joke and deliberately "leaves a a question as to meaning or intent." (reverse def #1 8-) /DOH!

    The inventor of Python (and all his parrots) proves himself (themselves) incompetent to talk about language structure or theory every time he says (they say) his blocks are not explicitly delimited.

    The blocks are explicitly delimited. It's just that the end-of-block isn't printable or likely to survive being emailed as plain text or posted on the web "casually".
    --
    Innocent people shouldn't be forced to pay for inferior software development.
    --"Code Complete" Microsoft Press
    1. Re:Python blocks *ARE* explicitly delimited by cduffy · · Score: 1

      It's just that the end-of-block isn't printable or likely to survive being emailed as plain text or posted on the web "casually".

      Eh? Last time I e-mailed a source file, the tabs might have been turned to spaces, but they still were there -- and that's all Python needs.

  307. Well spoken brother!!! by CrashVector · · Score: 1

    Thanx for your post - you saved me the trouble of typing in the same stuff!

    --Richard

  308. Re:hey! lay off Java by Anonymous Coward · · Score: 0

    yes i do. simple is beautiful.

  309. Re:One Downside -- by farmerzebra · · Score: 1

    ...and it has the added disadvantage of objects. Hey, at least its not Java which forces OOP on you instead of giving you an option... and harder to debug...

    Objects have saved my butt countless times. As for debugging, objects are easier to debug, in my experience. The codebase itself is easier to understand, better design is possible, and better design makes for easier debugging. All you really have to do to improve performance is limit the number of classes you use. The java platform is a good example of too many classes bogging some things down.

    It's possible to write crappy code in any language, under any design method. Objects try to make it harder to design spaghetti code.

  310. Re:Not all compilers support it, god-awful comp er by Heinrich · · Score: 1
    Object is functionally equivalent to void *, with a little runtime type checking added.

    It is not just a question about type checking but also of being able to restore correctly the original type in case of a heterogenous list. In C++, dynamic_cast does not work if the given type does not include virtual methods.

    Your program still crashes if you misuse it,

    This assumption is not correct. A misuse of void *, i.e. a wrong cast does not automatically crash your program. Unfortunately one of the greatest problems with C and C++ is that many problems of this kind are initially survived which, under some circumstances, might open interesting security holes.

    I just disagree with the claim that C++ *forces* you to use templates for generic programming by not providing alternatives.

    Well, I do not consider alternatives that cause me to lose type safety. void * was introduced in C to get rid of char * as a generic pointer type in the context of storage management. It is the correct type of malloc(). Fortunately, we have a new operator in C++ and do not need void * any longer except for some low-level tricks.

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

    1. Re:Not a fair comparison by Anonymous Coward · · Score: 0

      the C++ std::sort function doesn't use merge sort.
      It is an inplace sort so cannot be a merge sort.

      Stroustrup says that C++ sort function is not-guaranteed to be stable, has very good mean performance but can have O(n^2) performance in the worst case. This is a pretty good description of quick sort.

    2. Re:Not a fair comparison by Tharsis · · Score: 1

      According to this it's neither, it's an introsort which has O(n log n) worst case performance. Another interresting comparison between C and C++ sorts is given here

  312. USE THE SOURCE DUDE!!! by Anonymous Coward · · Score: 0

    To all who want to do anything with STL -

    USE THE SOURCE DUDE!!!

    And if you are having troubles wading though it all, get gimpel's PC-Lint or Flexelint, and use
    it. (you could substitue gimpel's product for
    any other static checker)

  313. Best tool for the job by Joe+U · · Score: 1

    Honestly, many people love to rush out and cram one library (or language) down everyones throat at a moments notice. The way to become a better developer is to use the best tool for the job at hand.

    If I need to whip up something quick, like a splash screen program for Windows, you can bet I'm using MFC. Why MFC? Cause I only need to pop up a splash screen, maybe a dialog box or 2, and I want this thing to be done in an hour.

    If I'm designing a new server app, I'm going to sit down and think over what I need to put in it before I jump on any library. (And no, MFC is not my first choice for this.)

    Sometimes it's not about code readability, or reuse or even good programming. It's about getting the job, that works to the spec given, done in the shortest amount of time.

  314. Threading (Re:Enterprise issues with STL) by amacbride · · Score: 1

    Having done a very large, multiplatform (NT and Solaris) project with the STL, the biggest issues we faced were problems with thread safety. Even some of the things that were purported to be threadsafe...weren't. (We found a bunch of bugs in the Microsoft and Sun compilers, and also g++.)

    I will say that it enabled us to get a system up and running quickly, but the debugging process (long error messages, obscure thread bugs under heavy load in a distributed system) was absolutely horrible.

    Hopefully, things are better now.

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

  316. Why on earth would you do that? by Homburg · · Score: 1

    At least, for the string? What you've written is exactly equivalent to:

    std::string foo;

    I can see why you'ld want to do that for built in types which aren't initialised by default.

    The problem is that std::string doesn't support null semantics, unlike char* - if you want it, there are classes that add null semantics to other classes (I think boost has one).

  317. Re:No (Doesn't Slashdot use Perl? comments.pl) by jerry924 · · Score: 1

    Does that make it any less useful for you? Jerry

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

    cough*kyoto*cough!

  319. need to reply by Anonymous Coward · · Score: 0


    I just feel the need to reply. So many comments I could comment on...

    All I can say is "AAARRRRRGGGHHHH" at the script-kiddies , people who tried it back in 1800's or 19whatever and thought the beta sucked, people who looked a book about the STL written by an Ada programmer, "I tried it once and thought it sucked", or people who have only programmed in language and think they know everything about every other language, etc.

    It's called get a BS degree in CS from an accredited institution so you actually know some theory. Don't settle for the BA or MIS degree. Apply it. Keep learning so you don't get in the rut of all these people that know it all, they don't, neither do I or you. Actually you should change your programming techniques as technology advances, go ahead try it, you'll be amazed. Much of what we already have learned will continue to become irrelevent, e.g. as HDs go the way of the dinosaur, etc. I personally don't want to be using the same code 10 years from now, forget code-reuse in the long term. As things keep getting faster there will be less and less time to keep "going back to my old code and modifying it a little bit to get it to work with a new " Face it, you don't have the time to mess around with assembly(i.e. old ways of doing things, compilers out code any assembly programmer now), insuring your code will perform to some big-O spec/re-writing the same old code for the 100th time when someone else has already done it for any thing you'll need it for, etc. You need to get it done and move on to your next project. The STL does that today. It will improve like all things. Use it, do it, move on.

    Personally I can't wait for Z++ and the SHIL (standard humanoid interface library) in 2015. ;)

  320. C++ coding style (Was:Partial List) by SLOGEN · · Score: 1
    The only encapsulation is true encapsulation.

    I agree with that, and the "typedef trick" is not true encapsulation. But if you "squint your eyes" it works, and I have a hard time respecting people who knowingly circumvent it. People who circumvent it out of ignorance will learn in time :).

    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.

    Oh, what an interesting discussion :). In my thesis, i'm extending the type-system of a language to include what i call quality-types, which express some quality about a value. The quality-type in not related to the normal-type of the value. This can be used to capture predicates such as:

    1. comes from user input (-> you have to check before you pass a string derived from it to system())
    2. has security level X (-> you can issue guarantees about the leakage of information)
    3. ...
    example:
    lattice {
    elements = system_checked, system_unchecked;
    system_checked < system_unchecked;
    }

    int system(<system_checked>const char *s);
    <system_checked>const char *check_for_bad_stuff(const char* s);

    <sysmtem_unckeced>int getc();

    int main(int argc, char *argv[]) {
    system(argv[0]); // error: arg 1 not system_checked
    char buf[10];
    sprintf(buf, "%i", argc);
    system(buf); // error: arg1 not system_checked
    system(check_for_bad_stuff(buf)); // OK
    }

    But, ultimately, a better solution would be run-time analysis, invocable an any time, there are many things you would like to check that it's not possible to check in a static-typed language.

    I'm flirting with adding code-anylysis and som type-check like features at "run-time" in a language like python. So your program would start by invoking the analysis, and then proceed. You could defer checking some parts of the program till later, skip the check for efficiency, ... Well, better finish my thesis first :).

    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.

    I generally believe, that people should code in a language they are proficient with, or get proficient at the language they code in

    That said, I don't deliberatly write code in complex ways, but if there's a mechanism that's "best" in my evaluation, I will use it, even if newbie's will find it hard to read. I prefer:

    return foo == null ? null : foo->stuff();
    over
    if ( foo == null )
    return null;
    else
    return foo->stuff();

    Every langauge has a "natural" way in which to program, and it should be used. I write in different styles in C++, JAVA, C, ML, ... I'm don't think similarity in implementation is a goal, although language independence of design often is (because the customer can't decide which language they want implementation in).

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

    I'm not sure I understand... std::auto_ptr is nothing near GC... And it sucks too:

    void f(const A*);
    void g(A*);
    auto_ptr<A> a(new A());
    f(a); // ERROR: cannot convert auto_ptr<A> to const A*
    g(a); // OK!!!

    Try looking at http://www.boost.org/libs/smart_ptr/smart_ptr.htm, it works MUCH better.

    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.

    That's very noble of you, but you are not allowed to mod on a topic you post on anyway :)

    --
    SLOGEN [ http://ungdomshus.nu : Sebastian cover music]
  321. Re:Binary incompatibility and buggy implementation by Anonymous Coward · · Score: 0

    The Intel icc implementation is pretty ok. I had no problems using it extensively with linux. I think it exists also for win. It's not free software though...

  322. Re:A few annoying bugs -- your own fault. by dorix · · Score: 1

    BUG 2: He's using malloc to allocate memory for C++ classes. Thus constructors aren't being called, so the list member object is incomplete, and garbage. This isn't an STL issue; it's a C++ basics issue.