Slashdot Mirror


Stroustrup Reveals What's New In C++ 11

snydeq writes "Bjarne Stroustrup discusses the latest version of C++, which, although not a major overhaul, offers many small upgrades to appeal to different areas of development. From the interview: 'I like the way move semantics will simplify the way we return large data structures from functions and improve the performance of standard-library types, such as string and vector. People in high-performance areas will appreciate the massive increase in the power of constant expressions (constexpr). Users of the standard library (and some GUI libraries) will probably find lambda expressions the most prominent feature. Everybody will use smaller new features, such as auto (deduce a variable's type from its initializer) and the range-for loop, to simplify code.'"

22 of 305 comments (clear)

  1. "Not a major overhaul"? by Godai · · Score: 5, Insightful

    I mean, it's not, but it makes it sound like C++11 is a minor update. Lambdas, auto, concurrency, are these minor updates? There's a lot of interesting stuff in C++11!

    --
    Wood Shavings!
    - Godai
    1. Re:"Not a major overhaul"? by genjix · · Score: 5, Interesting

      I've been using the C++11 for 6 months now in my own project (libbitcoin) and the new features and syntax really make your code sharper, clearer and better. C++ is no longer that unsafe language if you know how to code in it properly - you never really have to do any manual memory management if you use shared pointers.

      constexpr allowed me to create compile time constants that are the function of a bunch of complicated expressions. Sure, I could just put the result in the code, but by using constexpr (a far more expressive metaprogramming utility than templates) I can document where those constants came from by using code. Neat huh!

      Using variadic templates, I was able to write decorators that can be applied to any function. I simply wrap my functions with this class and then its operator() will be called before calling the passed in function object (which I can define using lambdas or std::bind now :)

      auto means I no longer have to type std::vector>::iterator in every for loop. Likewise for (const transaction& tx: block.transactions) is much more terse and clearer.

      The new features to the standard library are brilliant. Threading has never been easier: std::thread t(foo, x, y); will call foo(x, y) in a new thread. When I decide to finish the threads and then join them I call: t.join(); ... Simple.

      As libbitcoin is highly asynchronous, I don't like to use exceptions (which thread does it originate in? where does it get caught? .etc). C++11 now provides the header which defines std::error_code(). An error_code object can be tested as a boolean (to see whether the error is set or not) or compared against an enum value (which you define). They also have an error message (which if you defined the enum value it is set to, you can also set the message), and also you can group different error code values into broader categories! Really useful for asynchronous programming.

      std::atomic for a thread-safe counter (useful when you have multiple thread paths executing and want to see when they all finished - increment your counter by one after each path completes) and std::atomic for a thread-safe flag. ... That's off the top of my head. There are dozens of many small things like this. C++ was always my 'native' language, but now it's truly my home.

    2. Re:"Not a major overhaul"? by 19thNervousBreakdown · · Score: 5, Informative

      Don't forget initializer lists, variadic templates, non-static data member initializers, finally fixing that Template> (note the >>) thing, rvalues, nullptr, strongly-typed enums, constructor improvements (holy god we don't have to rewrite every fucking thing every fucking time or split off into an ::init()), user-defined literals which is crazy cool combined with templates and initializer lists, and lots of stuff I'm sure I'm forgetting about.

      Since starting on C#, I've kind of felt like I'm back in the dark ages in C++, even as it remains my favorite language. I've already started using a lot of these improvements, and while C++ still has it's rough edges, the improvement in "fun" while coding is massive. No more for (some_container_type<vector<map<int, string> > >::reverse_iterator aargh = instance.begin(); aargh != instance.end(); ++aargh) for me!

      --
      <xml><I><am><so><damn>Web 2.0</damn></so></am></I></xml>
    3. Re:"Not a major overhaul"? by swillden · · Score: 5, Informative

      auto means I no longer have to type std vector iterator in every for loop

      You didn't anyway. You type in "int" to loop over a vector.

      Only if you want to tie yourself to using a vector. Using a proper iterator costs you nothing in code space or execution time (because for a vector it optimizes down to just pointer arithmetic anyway), but means that at some future time you can replace that vector with a different data structure without having to modify the code that operates on it.

      --
      Note to ACs: I usually delete AC replies without reading them. If you want to talk to me, log in.
    4. Re:"Not a major overhaul"? by genjix · · Score: 4, Informative

      > What C++ compiler are you using?

      g++ 4.6 - standard in Ubuntu

      Two of the features I'm waiting on are class level non-static initialisers and templated typedefs. I've heard Microsof's C++ compiler has better C++11 support but I've never tried it.

      Beware that MingW has a bug so std::thread is disabled. I've heard mingw-w64 works better. You might want to also try boost::thread (same library essentially, except std::thread has move semantics).

    5. Re:"Not a major overhaul"? by martin-boundary · · Score: 4, Insightful
      C++ has always been about performance and low level control. However, having higher level constructs in addition is a good thing.

      Take goto, which is all that's really needed for modern programming. Using goto, you can implement subroutines (gosub like functions), while and for loops, etc. But each time you implement one of the higher constructs, your implementation will be slightly different. And if you force yourself to use the optimal implementation all the time, you'll just be writing a lot of boiler plate code. So having functions and while loops implemented as language constructs is a good thing. Similarly, std::thread + lambdas is a great addition.

  2. Re:News? by busyqth · · Score: 5, Funny

    That said, as a professional C++ developer working in HPC, this is exciting.

    Stop pretending and get back to your FORTRAN!

  3. and in the next revision... by busyqth · · Score: 5, Funny

    S-expressions, continuations, hygenic macros...

  4. Re:I want auto! by SpryGuy · · Score: 4, Insightful

    Prohibiting use of "var" is gross over-kill.

    There are times where it's use is not recommended, certainly. But even in those cases, it can lead you to the point that there's a "bad code smell" where methods aren't named well, variables aren't named well, classes aren't named well.

    var x = foo(); is definitely less readable.

    But var x = new ComplexObject(); is every bit as readable, if not more so, because you don't have a redundant "ComplexObject" in the declaration. You always know exactly what type "x" is. It's also very useful in cases where the return type is a complicated generic. it saves a lot of typing, and is definitely more readable.

    Here is a very good discussion on the benefits and uses of "var":

    http://resharper.blogspot.com/2008/03/varification-using-implicitly-typed.html

    --

    - Spryguy
    There are three kinds of people in this world: those that can count and those that can't
  5. Fascinating Software Engineering Challenge by Bookwyrm · · Score: 5, Insightful

    In some ways, a lot of what is being added to C++ makes me think of Scala, just less readable.

    While the additions and extensions certainly make things more interesting and potentially more powerful/easier for the *individual* programmer, I look forward to seeing what sort of interesting train wrecks happen when larger teams try to make use of these features. I certainly hope the debuggers are being updated to be useful when someone's written a template that uses a #define'd macro to specify a closure that is passed through an anonymous function, etc.

    This strikes me as the next generation's 'multi-threading' -- where almost every programmer claims they can handle multi-threaded programming, but very few actually do it well. Particularly in teams when interactions require coordination. Going to take a whole new round of winnowing the wheat from the chaff when it comes to finding developers who can actually use these features well without driving their coworkers insane.

  6. Not seeing (1) by SuperKendall · · Score: 4, Insightful

    I don't think you'll see a lot of people flaming C++, there just aren't that many people that care one way or the other anymore.

    I think some of the new features look nice but mainstream use has been shifting away from C++ for a while and I'm not sure I see these new features drawing many back...

    --
    "There is more worth loving than we have strength to love." - Brian Jay Stanley
    1. Re:Not seeing (1) by gbjbaanb · · Score: 4, Interesting

      Mainstream use is shifting back to C++ since Microsoft decided that C++ was batter than C# (or at least Sinofsky and the Windows team decided that was the case). Herb Sutter has done a lot of presentations on the new paradigm at Microsoft - do a quick google.

      Of particular note is the reason they're giving for this: in the datacentre native code reduces the amount of energy required to run your apps, and that adds up significantly if you're using dynamic or even JIT language.

  7. Re:I want auto! by godrik · · Score: 5, Funny

    chances that oracle will see the light? :-)

    Last time they saw the Sun, it did not end well...

  8. Re:I want auto! by 19thNervousBreakdown · · Score: 4, Insightful

    Because var still works within the type system and gives you compile-time errors, and casting to object is a massive sledgehammer that delays errors until runtime (with all of runtime error checking's glory, like only failing some of the time, which you can basically read as "never on a developer's machine, sometimes on TQA's machine, and always on a customer's machine (unless support is on the phone with them)"), and a stupid idea in general (I'm looking at you, Objective-C!).

    --
    <xml><I><am><so><damn>Web 2.0</damn></so></am></I></xml>
  9. Re:He's optimistic by grumbel · · Score: 4, Informative

    > But C++11 describes a standard that absolutely nobody has ever got anywhere close to, so I don't imagine that there's going to be a lot of drive to adopt it.

    All popular C++ compilers already implement large parts of C++11, so the chance of seeing widespread C++11 adaption in the not so distant future is pretty high. Also this wasn't really any different with C++98, which essentially no compiler supported on release and which then took a few years to gain widespread adoption.

  10. Re:In practice it's like a different language. by DeathFromSomewhere · · Score: 4, Insightful

    C with classes is a derogatory term used to describe programmers and code which wraps C-style code and various bad practices with classes. You end up with things like custom string and array classes, using memcpy instead of std::copy, printf instead of std::cout, FILE* instead of std::fstream, copy paste instead of inheritance and void* everywhere.

    --
    -1 overrated isn't the same thing as "I disagree".
  11. Re:In practice it's like a different language. by tibit · · Score: 5, Interesting

    Now be careful, because inheritance was not really intended for code reuse. If it does help with code reuse, that's a positive consequence, but it's not what inheritance is for, first and foremost. See Liskov substitution principle and all that jazz.

    --
    A successful API design takes a mixture of software design and pedagogy.
  12. Re:I want auto! by shutdown+-p+now · · Score: 4, Informative

    "auto" was always implemented, since the very first version of C, it just had a different meaning - it means that variable has an "automatic storage class" (as opposed to "static storage class" etc). Because automatic was the default, it was almost always redundant, but it did have a meaning.

    It actually goes way back to B, which only had a single data type - machine word. Variable declarations looked somewhat like C, but, for the lack of type, they started with the storage class instead, i.e.:

    main() {
      extern x;
      static y = 1;
      auto z = 2;
    ...
    }

    In C, we've got types, so you'd normally write "static int y" for a static local, and just "int z" for an automatic one - "auto" being implied. However, C inherited some of B's semantics as "default int" - i.e. if the declaration is clearly a variable, but it omits the type, assume that type to be "int" (i.e. machine word). So in C the above code snippet from B is actually valid, and declares x, y and z to all be ints.

    Then "auto" got inherited by C++, which dropped the "default int", making auto completely redundant - you couldn't write "auto x" in C++ anymore, and in all other cases where you could use "auto", like "auto int x = 123", it was always redundant. So when they appropriated it for type inference in C++11, it was technically a breaking change - it just wasn't ever used by anyone in production code in the old way, so nobody noticed.

  13. Re:In practice it's like a different language. by RCL · · Score: 5, Insightful

    So what? STL isn't suited for all possible uses, sometimes you need your own string and container classes.

    Don't be a zealot, pragmatic programmer should find the right trade-off between reusing code and writing an optimal one for a specific problem/area. Nothing can be optimal in all cases - sometimes you need to be as close to hardware as possible at the expense of unreadable/inflexible code (for me, those are the most interesting and challenging areas), and sometimes you only care about maintainability of your code by a disposable programming drone.

  14. Re:In practice it's like a different language. by QuasiEvil · · Score: 5, Insightful

    >Time to join the 21st century grandpa. FILE* leaks.

    Hell no. And get off my lawn.

    printf() isn't typesafe, but it's a fuckton more readable than all that cout formatting stuff. Also, the fact that it's not typesafe isn't really an issue if you don't suck - trivial unit testing will pretty much show any problems immediately. Besides, gcc/g++ is nice enough to warn you about egregious ones now.

    FILE* leaks? I assume by this you mean when sloppy programmers fail to close their files and you start burning through file descriptors. Sounds like a bug to me, and again, stop sucking. Or do what we do - throw an object with a destructor containing fclose() around it. Then you get all the awesomeness of of FILE* (including those awesome formatting commands like fprintf and fscanf) without the danger of your file staying open when something goes nuts.

    Why on earth would you want memcpy() to call anything? It's a low level byte move. Anybody with five minutes of familiarity with it should know that. If you wanted something different, use the assignment operator.

    void* have all sorts of applications, most recently to me in writing architecture neutral VMs where really all the native machine knows is that it's moving around some sort of pointer.

    Now the custom string and array classes? That I'll agree on. Troll on.

  15. Re:So what is a good book to learn C++11 by LizardKing · · Score: 4, Funny

    Dante's Inferno. Sample quote:

    Obscure, profound it was, and nebulous, So that by fixing on its depths my sight - Nothing whatever I discerned therein.

  16. Re:In practice it's like a different language. by TheRaven64 · · Score: 4, Insightful

    printf() isn't typesafe, but it's a fuckton more readable than all that cout formatting stuff

    Readable? Meh. Localisable? Now that is an important attribute. Consider this trivial bit of code:

    printf("The %s %s\n", colour, object);

    You want to localise this, so you wrap each string in a function that returns the localised version (by the way, gcc and clang have an attribute that you can put on functions that says if the output is safe to use as a format string in any case where the input is). So now you have something that looks like this:

    printf(localise("The %s %s\n"), localise(colour), localise(object));

    Okay, no problem. Now let's consider the C++ equivalent:

    cout << "The " << colour << ' ' << object << '\n';

    Harder to read? Maybe, but the tokens are all in the order that they'll appear in the output, so I'll give C++ that one. Now let's localise it. How about something like:

    cout << "The ".localise() << colour.localise() << ' ' << object.localise() << '\n';

    That's fine, right? No more complex than the C version. Well, almost. Let's make French the target language. We want to turn 'the black cat' into French. Now we have a problem. In French, the word order is different. The result we want has the colour after the noun. No problem in the C version, the format string is just translated as "Le %2$s %1$s". The arguments are reversed (well, it's a little more complex because you also need agreement between the noun and the article, but I'll skip over that for now - it can be solved in the same way). What about the C++ version? Well, because the word order is in the code, not the data, you need different code paths for English and French. And that's just with a three-word sentence. Now consider the kind of sentence that actually appears in a typical UI. Consider German word-order rules. Your simple C / Objective-C strings file has to be replaced by a huge tangle of C++ code.

    --
    I am TheRaven on Soylent News