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.
Yeah but this one goes to eleven!
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!
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.
C++0x is C++11. C++0x was a placeholder name until they actually knew what year it would be finalised.
Spelling mistakes, grammatical errors, and stupid comments are intentional.
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.
http://en.wikipedia.org/wiki/C%2B%2B0x#Features_to_be_removed_or_deprecated
Your comment caught some flack, but I couldn't help but make a similar observation as I read the spec. It seems that they are adding a lot of stuff to C++ that exists in C# (lambda expressions, delegated constructors, automatic deduction, initialization syntax, a dedicated null keyword, etc).
Of course, they added a bunch of stuff that's also NOT in C# (since it's not necessary in a high-level language like C#), but I am glad that they are revamping C++ to incorporate some higher-level functions. Now we just have to wait for compilers to start adopting the new spec...
You know, like how Clash at Demonhead and Mega Man 2 took place in "200X!"
And it looks like they missed their worst-case deadline by 2 years!
No, in hex (0x) you really can go to 11.
Nope, C++0x is C++ 2011. C++11 does not exist.
I am TheRaven on Soylent News
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
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!
The saddest part about this whole C++0x ordeal is that they're still just playing catch-up to C#.
True. In particular, C++ is light years behind C# in patent FUD. And C++ hasn't even started work on requirements for a 100MB "managed environment" for users to install before running their apps. Nor have C++ developers chosen a monkey species after which to name its 2nd-class-citizen cross-platform implementation.
And it shows they should never again make assumptions on finish dates. They never did get it done during the decade they targeted or assumed.
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.
...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.)
What's the patent FUD, specifically? I'm not talking about some obscure part of the Winforms API, I mean in the core language itself.
Any core language is almost useless without its standard and/or de facto libraries. Microsoft's patent policies on the libraries associated with C# (not just Winforms) are intentionally vague and confusing. Nobody really knows what conditions the patents may be used under, and by whom. This passive-aggressive stance on patents is a standard Microsoft strategy, and it's been pretty effective in general.
And you forget that C++ has a giant environment to install as well, but due to age, that is generally part of the OS as is.
Doesn't matter to the average user. If they have to worry about downloading and maintaining a huge pile of optional software libraries to run a sudoku puzzle, that's a hassle.
In fact, Windows Vista and 7 already come with .NET pre-installed, so there's no need to download anything to run a .NET app.
Hence the need to choose a monkey name for your 2nd-class-citizen project for non-Windows platforms.
C++ has a giant environment to install as well
No, it doesn't.
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.
Does it have a 64-bit compiler yet?
The AACS key is NOT 0xF606EEFD628B1CA427BEA93A9CA9773F
Pretty much everything new in C++ 0x was around in the Boost libraries before showing up in C#. (A lot of the Boost stuff is written by C++ committee members). Standards usually follow years behind use. (The SCSI standard is my favorite for that- you know a particular SCSI rev is obsolete when the standard finally gets ratified).
These day you don't even need Boost: most of the stuff in the standard is already available in most compilers, if you set the right switches. Heck, even Visual Studio has a lot of it.
Socialism: a lie told by totalitarians and believed by fools.
You're worried about hassle for the "average user" who runs Sudoku apps. These users are on Windows. For tthose who are on Mac, Macs have a good enough package installation system that it's not too big of a deal for packages to have prerequisites.
BBut anyway,why are you citing external factors to somehow prove that C# iis an inferior language? Its "goodness" is in no way diminished by the fact that few platforms have implementations written for them.
Le français vous intéresse?
In hindsight (I posted the same thing), it occurs to me they can still claim to hit the target range if they go in hex...
But then it should have been C++ 0x0x
BBut anyway,why are you citing external factors to somehow prove that C# iis an inferior language? Its "goodness" is in no way diminished by the fact that few platforms have implementations written for them.
Intrinsic "goodness" is not the only relevant factor unless you operate in an ivory tower situation. For the real world, you have to take into account all of the aspects associated with using any given language. This includes deployment, developer availability, licensing, performance, suitability for the particular problem to be solved, etc.
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>
Isn't D copiled by GCC? Why would it not have a 64-bit compiler (you mean a compiler for ia64?)?
Rethinking email
In fact, Windows Vista and 7 already come with .NET pre-installed, so there's no need to download anything to run a .NET app.
Cause I really enjoyed the latest .net Framework 3.5 and 4 security updates that was nearly 400 MB... Thank you MS!
Yes and in fact, if the constant starts with a leading zero, they should have really got it done by the end of 2007.
All I want is a secure system where it's easy to do anything I want. Is that too much to ask ~~ Randall Munroe
I wholeheartedly agree with your points, but would have to hand in my geek card if I didn't correct you on at least one point : "mono" means "monkey" in Spanish (Icaza, its creator, is Mexican), it is not a species of monkey.
It's /. after all :/
What do you mean that wasn't the 1911 standard?
I have excellent Karma and I am not afraid to Troll it.
Yep, that happens to be what makes it usefull for some kinds of software. If you want a managed language, use one.
Rethinking email
Obama and the democrats are slightly less in favor of serfdom than the republicans.
intel has a c++ abi standard.
Do you even lift?
These aren't the 'roids you're looking for.
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.
Cause I really enjoyed the latest .net Framework 3.5 and 4 security updates that was nearly 400 MB... Thank you MS!
I also enjoyed the way it spent over an hour pre-compiling assemblies during the update. Granted, it was on an old machine, but it still would have been ridiculously long on a modern one.
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.
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.)
Now we just have to wait for compilers to start adopting the new spec...
GCC supports most of the specs already.
Yes, D is good stuff indeed. You mentioned AA, but let's not forget Walter Bright, D's creator and all-around genius.
They already do, to varying degrees: Apache has a wiki entry describing levels of support.
grey wolf
LET FORTRAN DIE!
What's the patent FUD, specifically? I'm not talking about some obscure part of the Winforms API, I mean in the core language itself.
Microsoft made some veiled threats a few years ago, intimating that their deal with Novell for Mono was exclusive. No one is really privy to the terms of that arrangement, but it made a lot of people really nervous.
And you forget that C++ has a giant environment to install as well, but due to age, that is generally part of the OS as is.
C++ is quite capable of operating entirely without a run-time environment. It depends only on the C++ standard library and the C standard library, which, while implemented by the OS, are completely optional.
In time, modern generation languages will end up in the same category. In fact, Windows Vista and 7 already come with .NET pre-installed, so there's no need to download anything to run a .NET app.
But this is not the case on non-Windows platforms.
grey wolf
LET FORTRAN DIE!
C++ is the Lisp of Mordor - me
It's not that simple according to this page.
I know someone who was developing a medium-sized program in D and decided to start over in C++ due to compiler bugs and general lack of compiler maturity.
The AACS key is NOT 0xF606EEFD628B1CA427BEA93A9CA9773F
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.
C++ is one more than C, so, you see, it's plural...
(Assuming C > 0)
If you can't convince them, convict them.
If an API is written in a way where the user has to be "very careful", then it isn't written very well. There might also be performance reasons but I've found that you are rarely absolutely required to sacrifice safety, readability, etc, to attain substantial performance gains if you truly know what you are doing.
C++ is one of the more "safe" languages available if you use it properly. It's compile time safety features trump all other popular languages in my opinion (runtime safety is another story).
Unfortunately, in both C# and C++, eleven is an invalid value, but there was no exception handler, so...
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.
I immediately take it as the British English tendency to treat 'names of entities' as plural, as in "Apple have been evil for less than 5 years".
RETURN without GOSUB in line 1050
I really hate that attitude regarding C++. Yes, C++ has a learning curve. C++ isn't necessarily the best solution to a given problem. But if you know how to use it, you will be very productive.
Also from what I've seen, C++ can do just about anything that any other language can do, and more, in some fashion. To me, this makes C++ the best (but not only!) tool for most projects where I am not burdened by naysayers who refuse to learn a "difficult" language.
You mentioned scripting languages. Scripting languages are great for a variety of uses, but they terrible for others. They don't scale. They don't have much or any compile-time safety. They are typically slow.
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?
The comparison still doesn't make sense, because C++ and C# are languages on different levels of abstractions. You use C++ when you want to be close to the metal (and think that C is too simplified and requires too much hand holding for everything). You use C# when you're okay with a memory-safe, garbage-collected environment.
This is quite evident in feature design, too. For example, C# lambdas always automatically capture any variables from the outside scope that they use, and the lifetime of those variables is magically extended - this is possible because GC takes care of it. In C++0x, lambdas capture things explicitly (you can auto-capture everything used in the body, but that is also an explicit choice; default is "no capture"), and if you capture by reference, there's no lifetime extension for captured variables - if you need that, you have to manually use shared_ptr (or something similar).
Now we just have to wait for compilers to start adopting the new spec...
They already are. E.g. lambdas can be used in Visual C++ 2010 (released over a year now), and in g++ since 4.5. Similarly, auto, nullptr, rvalue references and static_assert are all available in current stable releases of both compilers. Most of the library is also there, so start using std::unique_ptr and std::shared_ptr today (and forget about TR1).
Thanks for the explanation. What a hell of imcompatible versions... I guess that is how it feels to program in very new languages.
Rethinking email
It comes from Java programmer, so be warned. (I don't know how much it applies to C# as well, as I am not very familiar with it. To be honest I don't feel that I'm know C++ well enough neither, but who does?)
My problem with C++ is that it's syntax is too complex, so it's impossible to write decent auto-complete feature. (I'm not impressed with the Intellisense in VS C++; or the one CodeBlocks). Also, that causes error messages to be less helpful, and I guess many incompatibility between different compilers is caused by this fact.
Also, the way it includes headers can be confusing at times, as putting classes in modules works different than putting functions in there. Also the fact, that it matters which direction declaration come feels archaic as well. (I don't feel it was justified to do things this way in the eighties. However I wasn't there writing compilers back then.)
Of course, the garbage collection of Java makes it unsuited for real-time applications. (And the fact, that "finalize" methods are often not called at all.) And I'm not very happy, that JNI has such a big overhead, but I think Java got a lot of things right with it's simplicity. Also, although agile people like to bash Java, I don't see that it were unsuited to that methodology, as the corporate culture isn't there in the language per se. And the verbosity and staticness gains you better IDE features (better auto-complete and refactoring and cross-referencing support; also, it makes code written by others much easier to get familiar with).
I wonder whether it would be possible to write a lower level Java, or standardise calling conventions for CPU acrhitectures yet to be created, without moving everything to a virtual machine.
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?
I'm a native English speaker who had just woken up when I wrote that :)
Le français vous intéresse?
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 ?
I don't use Windows anywhere but at work, so I'm pretty clueless about the situation. My work laptop has Windows 7 on it and I've had to download (myself) .Net Framework 1.1 and 4.0 for different things I run (Parker ACRView and Microsoft Expression Encoder). I don't know if those are included by default, and our IT guys just leave it out for some reason.
Nor have C++ developers chosen a monkey species after which to name its 2nd-class-citizen cross-platform implementation.
Monkey? I always assumed it was named after the disease teenagers get from kissing too promiscuously...
Paul "TBBle" Hampson
Paul.Hampson@Pobox.Com
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!
Those are all fairly common concerns about C++, but primarily ones made by inexperienced C++ users.
The complex syntax (particularly templates and the preprocessor) indeed presents a problem for writing helpful IDEs both in terms of autocomplete/refactoring and useful error reporting.
There is a plugin for MSVC called Visual Assist X that does a much better job than (at least 2008's) Intellisense. It's not free but myself and people I work with find it indispensable. It handles almost everything very well except for particularly crazy preprocessed constructs.
Header inclusion is really a very simple affair - all the #include directive does is paste the contents of the file in place. Everything else falls out of that. Forward declarations may seem archaic, but they allow you to be explicit about depending on skeletal declarations rather than full definitions (although this can admittedly get kludgy in some circumstances, e.g. typedefs), and they allow you to have a sort of cheat sheet of declarations that is separate from the implementation.
I'm not sure what you mean by the direction of declarations. As long as you avoid unnecessarily cyclic dependencies (which should be easy if you keep definitions out of your headers), you should be fine. I'm also not sure what you mean about the difference between classes and functions in "modules". Both classes and functions can be "forward declared". Nothing needs to depend on the definition of a function, but you need to see the definition of a class if you want to do anything more with it than hold/pass pointers/references of its type. Declarations can be repeated as long as they are the same. Definitions can not be. (and neither can typedefs, which is indeed irritating, but the new standard does improve on typedefs in various ways).
Java is built for virtual machines. By definition, I don't think it's possible to write a different sort of compiler that improves on the performance situation of a VM very much. If you were to attempt something like this, you'd be at best creating a subset of Java which essentially would be a restricted subset of C++ anyway, I think.
"Header inclusion is really a very simple affair - all the #include directive does is paste the contents of the file in place. Everything else falls out of that. Forward declarations may seem archaic, but they allow you to be explicit about depending on skeletal declarations rather than full definitions (although this can admittedly get kludgy in some circumstances, e.g. typedefs), and they allow you to have a sort of cheat sheet of declarations that is separate from the implementation."
What I meant, when to extern and when not to. I once struggled to convert extern functions to class methods. I can't cite the example, but it was plenty confusing for me.
And besides the language itself, the another problem is the standard library: it has so few things. Not even a proper String class that abstracts away character encoding, no standard way to create GUIs, parse XMLs. I had to do some small project in c++ recently, and I had to hunt for opensource libraries that do these, but unfortunately, the XML library used UTF-8, the GUI used UTF-16, and the free fonts I have found didn't support latin2 characters. Just finding an iconv, that runs on windows took 3 hours.
You should never have to use extern unless you are trying to interoperate with some external library.
Regarding strings, you're right, UTF support was tricky (although if you don't know std::string is just a typedef of std::basic_string, so abstraction IS there, to a degree). C++0x improves the situation considerably (quoting wikipedia):
There are three Unicode encodings that C++0x will support: UTF-8, UTF-16, and UTF-32. In addition to the previously noted changes to the definition of char, C++0x will add two new character types: char16_t and char32_t. These are designed to store UTF-16 and UTF-32 respectively."
It also adds both UTF string literal syntax and user-defined literals.
Regarding XML, I don't think it belongs in a "standard" library. Yes, it's common. It wasn't very common when the current C++ standard was introduced. But, it's a specific file format, not a general language/math/software feature. It might be "convenient", but there's something to be said for simplicity and keeping the standard library slim. It doesn't belong in the standard library any more than an image parsing library does. There are also many ways to write an XML parser, depending on what you are trying to optimize for (performance? memory? convenience?) That's pretty hard to "standardize".
Similar things can be said regarding GUIs. They are inherently platform specific and thus fall outside the domain of a general purpose, relatively low level compiled language like C++, in my opinion. This is even more so something that everyone has wildly differing opinions on how to implement. There is no "correct" solution. There are GUI libraries with immense amount of work put into them, many of them for C++ and cross platform (e.g. Qt) and they change rapidly due to changing requirements. For all these reasons it makes sense to keep such a thing separate from the language.
C++ is not supposed to be a convenient language. It's supposed to be a powerful, efficient language first and foremost. Convenience is nice, but when it interferes with the main goals, it takes a back seat in C++. This isn't necessarily a bad thing, it just depends on what your use case is. Do you want power, or convenience? (This is not to say that you can't write convenient constructs and libraries in C++, and C++0x makes that quite a bit easier still).