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

33 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 DeathFromSomewhere · · Score: 3, Insightful

    Don't wonder, hover your mouse cursor over the variable and behold the glory of tooltips.

    Now what happens when you change the name of a return type from a commonly used function? Have fun with your maintenance nightmare. If you are lucky the compiler will complain, if you are unlucky you break existing code without knowing it.

    --
    -1 overrated isn't the same thing as "I disagree".
  5. 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
  6. 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.

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

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

  9. Re:I want auto! by WARM3CH · · Score: 3, Interesting

    I don't agree. auto (or var) very rarely hide any information which is not immediately visible. For example there are trivial cases where auto (or var) just save extra typing:

    var my_object = new my_class();
    v.s.
    my_class my_object = new my_class();

    Here using var just saves a few key struck (or a lot, in case my_class happens to be a type with a particularly long name). In any case the type of my_object is perfectly known and quite visible so I think using auto is just fine.
    There are however cases that a complex type is used while we actually DO NOT care for the type per se. For example in C++ consider the case for a lambda function:

    auto my_fun = [](int i) { return i * i; };

    Here I actually don't care about the exact type of my_fun. All I care is that it take an int and returns an int which I can see clearly. Finally, another case could be situations in template programming where insanely complex types are used/generated and we don't want to (or even cannot) type them again and again. Also I guess in Java or C# you might get away by cheating and using an object (I hate it when people do that!) but we don't have that luxury in C++.

  10. Some idiotic stuff too by Daniel+Phillips · · Score: 3, Interesting

    I guarantee you will quickly come to hate the new "narrowing" errors, for example any time int converts to float inside initializer curlies, or double to float. As a language feature, this lies firmly in the category of wanking.

    That said, my code is all full of lambdas now, thankyou. On the other hand, lambda syntax is uglier than sin. While a lambda can do anything a lexically scoped nested function can, it is not pretty. Now obviously, there is no reason not to support proper lexically scoped nested functions, as GCC already does. Arguing that they are now unnecessary because of lambdas is, again, wanking. The practical fallout is that when you move a lambda-style helper function to global scope or to member status, you have a bunch of editing to do, to remove the ugly auto/lambda bits.

    Another big disappointment is, nothing was done to address the good features C99 has that C++ does not. Designated initializers and variable size array parameters, to name two. Wanking again.

    On the whole, there is too much wanking going on in the C++ stewardship process. Guys, you need to remember, C++ does not exist only as a means of compiling the STL.

    --
    Have you got your LWN subscription yet?
  11. Re:George Bjarne Lucas Stroustrup by dyingtolive · · Score: 3, Insightful

    I think he either forgot his LSD today, or took too much. Not sure which yet.

    --
    Support the EFF and Creative Commons. The war is coming, and they're supporting you...
  12. 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>
  13. 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.

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

  17. Re:In practice it's like a different language. by cheekyboy · · Score: 3

    Maybe because pure C++ with all its advances looks worse than random perl code or assembly.

    Im not asking for cobol like scheme, but come on, enough of the !@#$%^&*(){}|} magic

    --
    Liberty freedom are no1, not dicks in suits.
  18. 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.

  19. Re:For my next trick by shutdown+-p+now · · Score: 3, Interesting

    In one corner we have memory, which is 99% of the "resources" needed to be managed

    Go ahead, count the number of calls to "Close" and "Dispose" in a real world C# or Java app. Then get back to us with some solid number for that 99% claim.

    Simple example, open a file, write to it, let the dtor flush and close. If flushing fails, you won't know, because dtors can't return anything, and exceptions in dtors is a big no-no (because, incidentally, there's no GC to free the stuff). That's _wrong_.

    Suppose you're right, and you detect that flush failed during close. What are you going to do?

    Suppose furthermore that you have an exception in flight, and you've just had flush fail in your finally-block (assuming C#/Java). What are you going to do now?

    If you want exception safety, you need RAII, period. If you have RAII, you might as well use it for memory.

    Smart pointers are a lousy GC scheme that does memory badly (ref counting is inefficient, especially on MP systems, and cannot handle cycles)

    Those claims that refcounting is inefficient are old, but somehow they only show up in synthetic tests. In real world apps, something written in C++ is invariably faster and more responsive than alternatives written in managed languages. That's precisely why C++ is still used far more widely for desktop apps, and is used almost exclusively anywhere perf really matters (like games).

    And there's weak_ptr for cycles.

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

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

  22. Re:For my next trick by shutdown+-p+now · · Score: 3, Interesting

    Oh, and before you mention weak references (to be totally honest, I am not even sure if there is a standard weak reference in C++)

    std::weak_ptr in C++11. Been there for 7 years now (originally as std::tr1::weak_ptr), and for a few years before that in Boost.

    I'll mention that very few C++ programmers know what they are.

    That's the problem with those programmers, not the language. C++ is powerful and fast by design; that, unfortunately, also makes it complex by design. It's not a language for everyone, and Java and C# certainly have their very large niche. But C++ is a very powerful tool when used right.

    The syntax of C++ is so crowded that the language is only used for low level stuff where the extra 5% performance boost is a big deal.

    That's emphatically not true. I've repeated it several times already in this thread, and I'll repeat it again: most desktop software today is written in C++. Heck, even a fair bit of OS X software is written mostly in C++, especially if you look at the size of it (MS Office, Photoshop). The reason for that is that perf boost (relative to Java/C#) is more like 20% for common tasks; but, more importantly, there is a marked responsiveness improvement due to lack of GC. And responsiveness is some really subtle stuff - it's not quite the same as "fast", but it's very sensitive to stutter on the order of tens of ms (a delay over 100ms is already noticeable by the user).

    You can write good UI software in managed languages, but then you need libraries that are themselves written in native code, at least rendering and input layer. Otherwise you end up with a clumsy pig like Swing.

  23. Re:In practice it's like a different language. by RCL · · Score: 3, Informative

    I think he simply claimed that you have to deal with C++ written by C programmers all too often. That's my experience, too.

    I'm probably one of those C programmers. I use C++ features when I feel they are appropriate, but my definition of "the right thing" changed over years. I started to value custom-tailored solutions, often hardware- and problem-specific. No longer I'm trying to find (or create) code that would fit all (or even the most) cases, and micro-managed security is of lesser concern to me.

    I don't see what that has to do with the above. I suppose there are some rare cases where the standard library isn't appropriate, but are you arguing this is an excuse *never* to use it?

    There are always multiple tradeoffs involved, that's why I am very wary of saying "never". STL is no silver bullet, this is what I'm saying.

    E.g. STL is bad at managing memory, it's hard to make it NOT allocate it dynamically - yes, you can write a custom allocator for it, but STL allocators are inflexible and also - for some poorly thought reason - manage object construction, not just memory allocation, making this unnecessarily hard. STL is a template library, and templates produce separate implementation for every type used - whereas you can have a single void *-based container for all your POD types, with templates providing just minimal wrapper. Also, STL makes it hard for you to control how often memory (object instances) is copied - there's no way to influence its behavior if memory copying tops your profiler results.

    If you are developing primarily for desktop computers which are quite beefy (and also vague in terms of hardware), this may matter less (although it will never cease to matter - just think of all that slow code running on our desktops which eats the performance improvements we still (marginally) get, making desktop performance appear flat since 2004), but if your target is well-defined hardware-wise and if you know/set "upper bounds" for all the practical problem sizes your program is designed to handle, you can think of more optimal solutions for your case. This is one of reasons why you can still play the newest games on 2005 hardware (XBox 360) which hasn't even got an out-of-order CPU, while running the newest desktop software (not games!) on PC of the same era is problematic.

    To sum up, I'm not saying "never use STL", but I would not say "always use STL" either. People claim that using "standard" code helps you create more secure, robust, performant programs - but in my experience, you will end up running a lot of custom tools (all kinds of profilers and validators) anyway before shipping your binary, that makes the point of "performant/secure code by design" moot. When profiler tells you that some code in an STL container underperforms, reimplementing it - or even understanding why that happens - is harder than fixing/improving your own implementation, yet you'll probably have to do that anyway. And no one starts "from scratch" these days, each "low-level" programmer I know has their own set of STL-alike classes.

    By the way, your reference seems severely dated. Some of its complaints are still valid, but seem based on the state of STL support ten years ago.

    Well, it is perhaps improving with new "move" constructors and whatnot, but that's actually a problem: it's better to have cross-platform code with predictable behavior than code that is supposedly optimal everywhere, but which depends on highly varied implementations. What good is it for me to know that some compilers (e.g. gcc), on some platforms (e.g. x86), handle new, C++11-ready STL well - gcc isn't particularly good at optimizing code even for x86, and another compiler that is a good optimizer may not support the newest features and make my STL-heavy code suck.

    P.S. Also, STL (in implementations I saw) is written in quite unreadable, convoluted style - I always wondered why. This is of course less rele

  24. 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
  25. Re:In practice it's like a different language. by TheRaven64 · · Score: 3, Informative

    My example is a trivial example. Go and look at some real code. In big applications, we use this pattern in Objective-C all the time. It's a trivial way of constructing localised strings. Now go and look at the mess of template metaprogramming that people use to do the same thing in C++...

    --
    I am TheRaven on Soylent News
  26. Re:Uh. No. by Electricity+Likes+Me · · Score: 3, Informative

    Operator overloading is to address the ambiguity of having by-value and by-reference passing of objects being possible via different semantics in the language.

    If I have a pointer and write:
    ObjType* pObjRef =
    then it's pretty obvious I have an object reference.

    But but what does
    ObjType Obj2 = Obj1;
    actually mean?

    C++ defines this type of transaction as always being a copy operation. But an object is a complex datatype - doing a straight copy of all it's memory doesn't necessarily give me sensible behavior. So you need operator overloading to let you enforce sensible behavior.

    That you can also use it to create syntactic sugar or completely illogical behavior doesn't make it bad though. And absent a garbage collector, I'm not sure it actually makes sense to do what C# does and try and treat all object variables as references (in that when would you deallocate things?)

  27. Re:In practice it's like a different language. by sco08y · · Score: 3, Funny

    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.

    It seems like it would be a lot easier to just change the word order of the offending languages than to screw up perfectly good C++.