Biggest Changes In C++11 (and Why You Should Care)
Esther Schindler writes "It's been 13 years since the first iteration of the C++ language. Danny Kalev, a former member of the C++ standards committee, explains how the programming language has been improved and how it can help you write better code."
I could've sworn I was using it before then.. perhaps it was all just a bad dream?
The article is probably referring to the first finished C++ ISO standard, 14882:1998. Hardly the "first iteration" of the language.
The saddest part about this whole C++0x ordeal is that they're still just playing catch-up to C#.
Would love to use these features in the new C++, but unfortunately none of the major compilers support the new for-syntax, in class initialization, deleting members and explicit specification of base class methods.
Also I totally don't understand why enum class no longer casts to ints... it totally makes using binary flags impossible unless I revert back to using the old style enums. But then I need to do the ugly namespace myenums { enum myenum { foo = 4, bar = 8 ... }; } hack which makes nesting inside classes impossible -_-
I really like that they added new stuff to the language but ...
Have they *removed* anything at all from it? That's the only way I could get interested in that language again.
I am glad that C++ is still evolving. That last major improvement I remember was the addition of the string class. Then shortly after that my professional focus moved away from C and C++ and towards higher level languages (.NET, PHP, Python, Java, etc...). I just recently started my own personal project so I decided to relearn C++ again, and I noticed there is a fair amount of new stuff that wasn't there before (or I was never taught)
If something is so important that you feel the need to post it on the internet... It probably isn't that important.
Lambda expressions!
Well, you'll be on the losing side so I guess you have a reason to worry. Did you know they are talking about the PS4 coming out in a few years?
Looks like C# from a few years ago. Honestly, it's really good that they're moving C++ forward, it's been lacking these features when other languages have embraced them for some time. I see they still use a plethora of ugly ass underbars, though.
This is news for nerds. Stuff that matters. I thought /. abandoned this stuff ages ago...
Slashdot - News for Nerds, Stuff that Matters, in ISO-8859-1 Has just realised that beta makes this signature redundant
C++ goes all the way to 11. It's one louder than other languages.
Let's see how long until Stallman posts a long text criticizing it all...
And C++0x? ( http://developers.slashdot.org/story/11/03/26/1949225/ISO-C-Committee-Approves-C0x-Final-Draft )
If the "alternative syntax" from PHP were allowed, the language could even become legible. What I see is still a write-only language.
Nae king! Nae laird! Nae yurrupiean pressedent! We willna be fooled again!
I was under the impression that bitfield layout was implementation-defined, and that's undesirable if I want my project to compile on different architectures. The page you linked includes the phrase "Microsoft Specific" around anything mentioning layout, which illustrates my point.
I was also under the impression that code generated by compilers for reading and writing bitfields was still dog slow. Has this changed?
Yeah, if we just ignore C++11 the world's problems will go away.
My other account has a 3-digit UID.
Is APK in charge of their naming convention or something?
Good luck with C++ 11 when you're stuck out in a field tending the crops for your lord, serf!
http://en.wikipedia.org/wiki/C%2B%2B0x#Features_to_be_removed_or_deprecated
They'll be using it to implement HTML 5.
I love had back in the day C++ advocate sneered at ADA due to that fact that ADA was "designed by committee". Now C++ is the ultimate example of a design by committee language. And that committee is huge.
Puzzle Daze is now my job
After many many years of C and C++, I jumped ship to C#. I don't really enjoy going back to C++ when I have to.
C++ is a ugly beast, ok ok it was (is?) important and very used and it will always be around, but today we have far better choices than it, one of them being D (http://www.digitalmars.com/d/). Which receives collaboration from many number of C++ evangelist, to name one of them: Andrei Alexandrescu.
It's been awhile since I've had to do any C++, so maybe I'm just missing something, but it seems like either there's a lot of retarded functionality here, or there's a lot of TFA which introduces a feature, even motivates it, but doesn't actually explain what the new version looks like. For example, with "Rvalue References":
Ok, first, what? I thought standard library string implementations were supposed to be efficient, and include some sort of copy-on-write semantics, which would (I would hope) make the above a shuffle-pointer-around instruction instead of a copy-data-around instruction.
Second, here's the newer, better syntax:
Regarding the first comment, no, I really don't, unless the point is that this is what the code for "moving" would look like if implemented in older versions of C++. But also:
Ok, cool... But where is this used in the "moveswapstr" example? Does this make the "naiveswap" example automagically faster? Or is there some other syntax? It doesn't really say:
The C++11 Standard Library uses move semantics extensively. Many algorithms and containers are now move-optimized.
...right... Still, unless I actually know what this means, it's useless.
It looks like there's a lot of good stuff here, and the article is decently organized, but the actual writing leaves me balanced between "Did I miss something?" like the above, and enough confusion that I'm actually confident the author screwed up. For example:
Great! Awesome! Of course, this arguably should've been there to begin with, and the 'auto' in front of these variables is still annoying, coming from dynamically-typed languages. But hey, maybe I can write this:
Instead of:
It's almost like C++ wanted to deliberately discourage abstraction by making it as obnoxious as possible to use constructs like the above. Anyway, that's what I expected the article to say, but instead, it says this:
Don't thank God, thank a doctor!
C++ is a brilliant language at its core. The only glaring flaw was the default copy constructor and the woes of casting with multiple inheritance. Looking back, the redundant header vs. implementation file declarations is also a bit tedious. However, I'm willing to overlook these as minor flaws in an otherwise good standard.
Sadly, STL and the standard C++ library are C++'s Achilles Heel. The container libraries were overly complex and suffered the woes of C++ template limitations. Remember those STL container compiler errors where a single type name requires the entire screen to render? iostream while innovative ultimately proved less practical than stdio, and is not as good as contemporary solutions when it comes to string localization, where parameter position is locale dependent.
Most importantly, the C++ library is woefully inadequate. What makes Java, .NET, Pearl, Python, etc so great is the library support. In my opinion, way too much emphasis was placed on garbage collection in discussions around C++, and not enough around robust library. To be fair, platform issues back then made this a big challenge. However, had their been an effort to create an industry standard (free) robust library for C++ that was as feature rich as Java and Net, we'd see more C++ programming today. (Yeah, I know there were attempts at this, but none of them made it into the standard.)
As a C++ programmer who went on to projects in the managed-runtime languages, and recently due to platform requirements has returned to active C/C++ development, I am amazed at how my experiences with those higher level languages now influences my C++ writing. I credit those Java and .NET experiences with helping me now avoid all of the C++ pitfalls that lead to problems. The resulting C++ is much more elegant than what I used to write. I enjoy the raw power of native code, although for most applications, it is not practical.
While you live your life in fear for a hypothetical future scenario, I'll try to live a happy life in the present instead. If your fears come true, we'll probably die at about the same time anyway.
My other account has a 3-digit UID.
C+=10
?
Do you have ESP?
Do not read this article, it makes C++0x look bad by giving terrible examples of the new features. Even features I've been excited about look stupid after reading this. The article shows how *not* to use a lambda expression. A regular for loop would be better here. Using "auto" on int and long does work, but defeats the purpose. The second example of auto doesn't even make sense since it doesn't actually include the word auto. It should be something more like: auto ci=vi.begin();
Just ignore this and go to Wikipedia or Google.
What is the big fuss about getting a garbage collector anyway? Why does it even matter? Good C++ code shouldn't need a garbage collector. If memory was allocated within an object then the destructor should be taking care of it. And with shard_ptr (which people should start using) it's taken care of within there anyway. Is this wanted so everyone can start coding sloppy C++ and forget about the delete calls? I suppose for those using some 3rd party library that behaves poorly and is totally out of your control it could be nice to stop that from leaking all over. Still, it should have been done right in the first place.
I suppose there might be some argument for preventing excessive memory fragmentation. Is there some other benefit to having one?
Fear is the mind killer.
What about a standard for mangled symbol names (implicitly covering calling convention) to allow cross-compiler linking, and attributes for declaring symbols exported or imported from the library or module.
...if I'm not a C++ programmer today?
I stated as a C programmer in the 1980s. I've used three different object-oriented extensions to C, and C++ was neither the first nor the best of them. I'm not in an industry (like video gaming) that pushes me toward C++ with any pressure at all. Every few years I take a look at C++ and conclude that it's safe for me to continue ignoring it.
Is there anything different this time around that would change this, that's easy to explain to someone who's not already a C++ programmer, and doesn't have the context/history of one? Could someone please summarize?
(Genuine and sincere question there, FWIW.)
Ah, the C++ committee. They've added lots of l33t features, and haven't fixed any of the safety problems. You can still get raw pointers. You still sometimes need them. The language-level arrays are still unsized, like C, and there will still be buffer overflows. (Yes, if you do everything the "C++ way", buffer overflows are much less likely. Now try to use the Linux API. There are too many places where the programmer has to be "very careful". People who think that's OK should be put on maintenance programming for a year.)
C++ remains the only major language with hiding ("abstraction") but without pointer safety.
They can't because it would break people's code
Then perhaps C++ and Java are overdue for a flag day. Visual Basic had one from VB6 to VB.NET, and Python more recently had one from Python 2 to Python 3.
GCC has supported many C++0x features for quite some time now.
My personal favorites are the auto keyword, particularly when used with iterators, enum classes & lambda functions.
Oh, and #include :
uint32_t, int64_t,
Many other features like regular expressions are neat but have been available with the Boost libraries for a long time anyway.
That was supposed to be
#include <cstdint>
What do you mean that wasn't the 1911 standard?
I have excellent Karma and I am not afraid to Troll it.
Obama and the democrats are slightly less in favor of serfdom than the republicans.
One of the best things that I see as a CS educator is that the threading package is now part of the STL. Teaching threading using PTHREADS always hid the concepts in a layer of obscurity. And usually, if something's obscure when you teach it, it will be a source of mistakes for novices and pros alike. Just the simplicity of async() and the creating of threads and mutexes makes this worth the price of admission.
The first sentence is true. It does not imply the second, however.. C++ was widely used in production before it became an ISO standard, so in one sense it was "out of development" before being standardized; on the other hand,it remains actively under development today (which is why we are talking about a new version of the standard), so no matter which side you look at it from, the first ISO standard isn't a good dividing line between the language "being in development" and it being in some other state. The first ISO standard for C++ wasn't the first iteration of the language in any meaningful sense, it was just the first ISO standard.
In soviet Russia, C++ hates you. Scratch that. C++ just hates you.
Would love to use these features in the new C++,...
Why? What is it about these new features that will make your job easier, your code more reliable, and easier to be maintained? Or do you just want to use those features because they're "new" - for C++ that is?
As a long time C++ guy (Borland C++ days), I look at some of these features and think "so what?" (Lambda functions, please.) I'll probably never use them. IMHO the last truly useful feature that C++ added was Templates which lead to the STL and made my life much easier... I stopped reading at this point... .
Let me stop you right there for a second. Proper utilization of lambdas and closures pretty much make a lot of design patterns (template, strategy, visitor, for example) unnecessary in many contexts. This obviously will have an impact in how you write/use templates. Furthermore, lambdas and closures help with shrinking class hierarchies even further than delegation alone.
Yes, we had functors before, but now you neither need to define functors classes/structs defining 'operator()', nor have to invoke new on them. That is substantially less typing to achieve the same without loss of generality, semantics or performance. We know from industrial evidence across multiple programming languages (or you should know) that this type of facility, when used properly, reduce complexity and the introduction of new bugs. It helps you focus more on the algorithms at hand without worrying about the boiler-plate that it is needed for its setup.
. This might look trivial in contrite pedagogical examples such as the one found in the wiki section of C++0x#lambdas found here. However, with real algorithms, one typically have to employ more than one functor. That's where the brevity of lambda expressions pay.
What is happening to you is that you have never done actual work with a language that supports lambdas. And as such, you cannot even imagine how these thing alone (when used appropriately) make code cleaner, and more bug-free.
In the end, you will know this until you use them in work/real-life scenarios. Until then you only have an opinion based on subjective feelings, not from-the-trenches facts. Give them a HONEST, laborious, nontrivial try, if not in C++ at least in some other, non-trivial work on another programming language, and try the same algorithms without them.
After the exercise, you might still think they are useless (and I would still think you are wrong). But at least you will have a hands-on basis for your opinion (as opposed than just puffed air.)
C++ have had...
Rather than
C++ has had...
?
C++ is the Lisp of Mordor - me
If Mozart wrote a Music Theory textbook, it would be delicious to read but impossible to use.
C++ is a great language, but it's impossible to use because it is fussy and complex. Real programmers don't have time to waste fooling with it and don't need to prove their chops to anybody.
Why didn't the C++ committee help to define a simple-to-use C++ scripting language subset, that we could actually use to write real-world code, quickly and efficiently?
sc
Nobody seems to have posted this useful reference yet:
http://wiki.apache.org/stdcxx/C++0xCompilerSupport
If anyone knows of a better one, please correct me.
I suppose defining the number of bits in types would be too much to ask? They give an example that uses an LL suffix for long long. I assume this means a 64bit integer. Would it be too much to define something like int16 or int_16? We have lots of code that uses typedefs to get these, and different projects sometimes define them differently. I know they'd argue that it breaks existing code - since people have already defined these types - but search and replace could be used. Perhaps they could provide a migration tool like Python did from 2.x to 3.0.
Speaking ONLY for myself; I read the FA, and I still see no significant reason to move away from standard c.
Know what would make me move? A syntax identical to the Python 2-series that compiled down to machine efficiencies similar to c. Now that's a beautiful syntax, a real step in the right direction. If I was writing it, I might be a little more strict about the indentation, so as to prevent things like lambda expressions, space/tab confusion, and single-line run-on, but overall, it's really, really nice as is. Add a good compiler and build in some portability, and I'd bite.
But... until then, I honestly don't think there is anything really worthwhile I could do in c++ that I can't do in c, generally at lower memory cost, higher speed, fewer "black boxes", and better portability. Which is not the same thing as saying there isn't anything unique to c++... just that the "good stuff" doesn't really add value I don't already have access to, albeit using much finer-grained techniques.
Objective c is pretty much the same... I find that the whole idea of objc is highly overrated, most of the added features are time- and memory-adding crutches... just a thin layer added to c that pressures you to use a messaging model you could have easily implemented yourself if you needed it, which you likely wouldn't -- if OSX wasn't chock full of it. :^)
On the Mac, I write an objc wrapper that talks to the OS, then write the core code in c. The only projects that I really write c++ for are those that arrive on my desk already written in c++, and which need my attention for porting, upgrades, etc. and even then... c++ methods end up wrapping c, generally speaking.
From my perspective, c++ and objc are both solutions seeking non-existent problems; solutions with fairly heavy penalties and which create overcomplicated implementation paradigms that take the focus away from the problem at hand. Too much emphasis on making programming "easy" and not enough on making it good. When I have to put the details together, I have to care about them. When I depend on the compiler to write part of the code for me, I'm going to get mediocre performance from a one-size-fits-all model without any real option to do anything about it. And I'm not just talking about code generation, although that's a problem too: I'm talking about managing the stack, making sure megabytes of cruft aren't glued to the application because some built-in capability incurs dependencies upon a whole series of frameworks or libraries, not having to fight the compiler-writers academic preconceptions about globals... I just prefer a finer degree of control, it suits me well.
And... yeah, I'd write in assembly if I could, there's another whole layer of speed, size and related benefits to be had there, but the portability issues, even within the same OS, are just too troublesome unless the code is for a controller where I know the hardware isn't going to change. Now *those* are fun projects.
I've fallen off your lawn, and I can't get up.
Proper utilization of lambdas and closures pretty much make a lot of design patterns (template, strategy, visitor, for example) unnecessary in many contexts.
I love lambdas but I don't have a lot of experience using them in large projects. I use the Visitor pattern a lot so I'm really curious to learn how lambdas can be used to avoid it. Can you post an example? Thanks!
Read a byte, test the bits you want (with classic C style binary ands) and save the results in bitfield values.
Without C-style enums, how would one define constants for the bits that one wants to test and then efficiently use those constants?
C++ still is C compatible.
C garbage collection is awful because double deallocation for example does not cause an immediate error, but can produce an error much later.
Of course you can try to work around that using debug allocation libraries, which make your program run 0.01 as fast, and which probably are not the first idea of a newcomer to the language.
Of maybe 4 a bit larger C++ projects I had, 3 had major problems which might have been related to this behaviour, and I was able to solve the issue only in my last project out of these 3.
Hey don't blame me, IANAB
Yes, we had functors before, but now you neither need to define functors classes/structs defining 'operator()', nor have to invoke new on them. That is substantially less typing to achieve the same without loss of generality, semantics or performance.
And you save even more typing because the damned things are almost impossible to comment properly.
I'm being a bit facetious, as I think any industrial-strength programming language ought to have lambdas, but I think they are far more useful to library and algorithm developers than application developers. I've been on both sides of that divide, and while I grant lambdas are useful and elegant, I've also seen them used in entirely inappropriate ways by application developers that have made their work hard to understand and even more difficult to debug.
For example, while g++ mostly supports the new standard I'm pretty sure gdb doesn't allow you to set a breakpoint in an anonymous function. Until it does I would say they have no place in application development, or only under the most draconian coding standards that prevent the kind of unpleasantness you get when a junior developer realizes all the kewl stuff they can do with them.
Blasphemy is a human right. Blasphemophobia kills.
Does naming them verbosely, and having similarly verbose names of parameters, help? Sometimes I get annoyed by that in Lisp and its variants, but that plus a block comment illustrating its purpose seems like it ought to be sufficient. Am I missing something in what you were looking for?
Still no garbage collector. //where expression's type can be figured out compile-time.
Lambda's are written like: [&varInScopeYouWantToUseInside](arglist)->returnType { statements }
(If you think this looks confusing, atrocious and quite unlike any other lambda for no apparent reason, you just have to suck it up and accept that C++ has entered the Century of the Fruitbat.)
Type inference: auto varToDeclare = expression
Finally. I love this, and if you're like me tired of writing "complicatedClassName x = new complicatedClassName;" you will love it too.
Since the designers were afraid that people would get confused between "classN var(constructorArgs);" and "structN var = {initer};" they've decided to add "classN var {constructorArgs};". This made me check whether it was April 1st, but no. Be prepared for "Ctor(args) : member { memberArgs } { statements }"
Often in C++ you find yourself forced to declare a constructor like "Ctor(){}". But now you are allowed to say "Ctor()=default" which is, as any fool can plainly see, clearly more efficient and relieves the programmer of this heavy burden. Works for destructors as well. In addition, you can now delete functions with "func()=delete". Now you only need to delete operator= and the copy constructor to make your objects uncopyable.
Because NULL isn't typesafe (except on systems on which it is) nullptr was added. Why they couldn't simply require NULL to be typesafe is beyond me, but I suppose that's only one #define away.
Constructors can now delegate to another constructor in the same class with Ctor() : Ctor(args) { statement }
Rvalue references are now available, declared with two && instead of one &. Since an rvalue is temporary this can save you from unnecessary object copying. Suppose you have "lval1 = lval2" - then a copy must be made from all the data in lval2 since this has copy-by-value semantics and lval2 could be referenced later on. But in the case of "lval = rval" rval is inaccessible so if it refers to its data by a pointer, you can just move the pointer to lval.
The runtime library. .join() or leave them alone with .detach() (which is called by their dtor). Mutexes and other data protection objects have now been standardised.
Launching threads now works as in other languages (hype about operator() is just that, since interally those are just functions too of course). You can wait for them to finish with
shared_ptr is a refcounting pointer type. VB had this in the early nineties, but better late than never. Note that if you use these with objects that do their own refcounting, this can be either more efficient (since it potentially saves a virtual function call) or less (since you'll have to effectively keep two reference counts). And they cannot be shared with anything other than C++ at the moment. unique_ptr doesn't keep a refcount but instead tries its best (compile-time) to keep you from obtaining two references by accident.
Given a set [a, b> (where a and b are references to the beginning and the just-beyond-the-end of the set, like "int a[10]; b = a + 10") you can now ask all_of(a, b, lambdaPredicate), any_of( ditto ) or none_of( ditto), which all return a boolean value as you'd expect. copy_n(source, elements, destination) does what you think it does and is hopefully simpler and hence safer than past constructs. You can now quickly fill an array a[10] with integers using iota(a, a + 10, 1). It's a shame that these all have to use C-ish syntax, instead of a cleaner object-based syntax, but I suppose you cannot have everything since C++ doesn't support extension methods. (At least not with normal syntax. It is common in libraries to use | for this but even though the C++ committee generally doesn't shy away from chtulhuesque syntax, this was clearly a bridge too far.)
If these changes seem somewhat underwhelming, I'd recommend you don't read the last paragraph of the article.
For example, while g++ mostly supports the new standard I'm pretty sure gdb doesn't allow you to set a breakpoint in an anonymous function. Until it does I would say they have no place in application development, or only under the most draconian coding standards that prevent the kind of unpleasantness you get when a junior developer realizes all the kewl stuff they can do with them.
VC2010's debugger allows breakpoints in lambdas. Just sayin' ...
...in 1995 when I saw there was nothing of interest in it. If I want to do system level stuff, I'll use C. If I want to do object programming, I'll use Java and/or Go. I don't see the need for a language that mixes both except as a confusing and hard to maintain broth. Do you pass your food through a mixer before you eat it ?
Non-Linux Penguins ?
Yes, we had functors before, but now you neither need to define functors classes/structs defining 'operator()', nor have to invoke new on them. That is substantially less typing to achieve the same without loss of generality, semantics or performance.
And you save even more typing because the damned things are almost impossible to comment properly.
I'm being a bit facetious, as I think any industrial-strength programming language ought to have lambdas, but I think they are far more useful to library and algorithm developers than application developers.
I disagree. One of the last projects I worked with (Java, not C++, however) we had to pass n anonymous "transformer" objects that would operate on data pulled from a database, n and the actual transformations dependent on particular conditions. For all cases where n > 1 this was hideous as we did not have lambdas in the 1.5/1.6 version of the language. Everything else in the application worked and looked wonderfully except where we have to create/add anonymous "transformers". Lambdas would have been extremely useful here, in application development.
Other examples have been with common exception handlers (which without lambdas, is incredibly hideous) or event listeners in GUI development. With other JVM languages that support lambdas (say, Groovy or Mirah), this type of library and application development work is trivial and elegant (ergo, less prone to bugs.)
Same applies to any language that does not support lambdas. Once you have them, anywhere where you have to structure your class hierarchy to include composition with the purpose of refining/extending pieces of an algorithm, that's a possible (possible, not certain) candidate for being replaced with a lambda.
I've been on both sides of that divide, and while I grant lambdas are useful and elegant, I've also seen them used in entirely inappropriate ways by application developers that have made their work hard to understand and even more difficult to debug.
For example, while g++ mostly supports the new standard I'm pretty sure gdb doesn't allow you to set a breakpoint in an anonymous function. Until it does I would say they have no place in application development, or only under the most draconian coding standards that prevent the kind of unpleasantness you get when a junior developer realizes all the kewl stuff they can do with them.
Hmmm, but that argument can be made with any other programming language construct or syntactic sugar in any programming language and in any context. Everything is open to abuse by the inexperienced or incompetent. There is a valid assumption about the level of competency that one must expect from developers. If they fail at that (and create abominations with a programming language, or a programming language feature), that's more a failure on the developers than on the design of the language.
Case in point, Gosling is still adamant about removing operator overloading from Java because "it's dangerous". And that is a stupid thing to say. Really, it really is. Yes, it can be open to abuse. But then again, that's why, in Java, we have to do this abomination:
Proper utilization of lambdas and closures pretty much make a lot of design patterns (template, strategy, visitor, for example) unnecessary in many contexts.
I love lambdas but I don't have a lot of experience using them in large projects. I use the Visitor pattern a lot so I'm really curious to learn how lambdas can be used to avoid it. Can you post an example? Thanks!
Every replacement has to be done in a case by case basis. Not all instances of those patterns can be replaced with lambdas.
Using the visitor sample from here, one could do the following (trivial example, I know):
can be replaced with this:
Obviously this is a trivial example. For real-world examples, one has to make an engineering decision of whether to replace a particular pattern or composition construct with a lambda, depending on a lot more factors than just coding aesthetics.
But that's not really replacing the Visitor pattern, is it? There is no double-dispatch in the lambda example. Thus I can't pass around a Visitor object and invoke it on arbitrary objects. I must pass around a concrete lambda. This is certainly useful in some cases but what it's really replacing is a struct of operations, not a full-blown Visitor.
Still, thanks for the example!