An unthinking programmer's guide to the new C++
Raising the standard
Agentless Backup is Not a Myth
Stob
So what’s all this about a new C++ standard, Verity?
Why you asking me? I know nussing. I’m down to write ‘Porcine influenza — a programmer’s perspective’ this month.
Don’t fib.
Oh very well. The enthusiasts imprisoned in the ISO C++ bunker are reputedly on the point of lighting a white smoke bonfire to indicate they have a new version of C++ ready. It’s provisionally called ‘C++0x’, where the ‘x’ stands for the year of its release.
This being 2009, there surely cannot be much doubt, can there? I mean, next year will surely be too late for an ‘0x’ standard?
Actually the C-plus-plusers point out it could be delayed until 200A, or indeed until 200F.
D’oh! How could I forget the joys of hexadecimal-based humour? No doubt about it, those C++ guys have still got it. But I guess this will be a conservative little standard, dotting a few semicolons and crossing the odd +?
By no means. This is to be a grand simplifying standard, making the old language accessible to dribbling dolts like you and me, who have so often struggled in the past.
Sounds wonderful, dribbling excepted. How about an example?
For example, what was the first bit of C++ that ever gave you trouble? Before you found out about multiple inheritance or default copy constructors or template template parameters?
Well, now you mention it, I never really got the hang of references. Couldn’t quite see why we needed them, what with the blessed K&R having bequeathed us pointers.
Exactly. You will be pleased to hear the new standard addresses your confusion head on. Whereas the old C++ let one write this
int& r1 = i; // i is an int
the new C++ one can do this:
int&& r2 = foo(); // foo() returns an int
Neat, eh?
I think you may have skimped a little on your research there, Verity. I’m pretty sure you were always allowed to call functions foo(), pretentious though it is in a Tech Model Railroad Club sort of way.
No, silly. Look at the declaration of r2. Look at the double ampersand.
Eughh! Cripes! I had noticed that but I thought that must have been some sort of typo that had unaccountably penetrated El Reg’s usually impeccable proof-reading system. So what does that mean? Some kind of reference to a reference, I guess? Somehow r2 is extra referency?
Nope.
And?
Well, I think it is really for passing big structures into functions. You know how those OUT parameter references you get in some languages, for when you need extra return values? And that have no meaningful value when passed in? I think these rvalue references are in some sense the opposite. You use them to make an IN parameter, but instead of being passed by value, it is a reference to a value that is about to die. You can trample all over it, because nobody will use it again. But it doesn’t cost loads and involve making copies as passing-by-value does.
I must say that was about as lucid as the text of a software licence agreement and half as amusing. Is there anything else to which you would like to draw my attention?
Ok, dig this new syntax:
int i = {}; // initialise an int
Don’t tell me. I can guess. It declares i and initialises it to the body of the first function that I thought of.
Nearly right. It means
int i = 0;
but brings the twin gifts of prolixity and obscurity to the party.
So why would they bother to… Oh, never mind. Bound to be some template tomfoolery. Presumably it works with pointers, like this:
int* p = {}; // initialise a pointer
// same as
int* p = 0;
Right?
Wrong. In the new C++, you have to write
int* p = nullptr;
Oh no. You are not getting me like that. That is what we used to write in C. These days you have to write a zero, or produce a letter from Andrew ‘Lookup’ Koenig letting you off.
That is not what we used to write in C. We used to write NULL in C. Do pay attention or I will send you back to learn your regex rhymes. Now, can you guess what this is?
auto i = 0;
Wait a moment. I have come across auto thing before. Isn’t it a K&R keyword meaning the variable declared in the common segment of a different other FORTRAN program?
Nearly. It means that you don’t have to bother to declare the int type — the compiler guesses it.
Bully for the compiler. Actually, I think I’d rather type int and save keyboard wear.
You can also use it to declare iterators and stuff
auto it = stlContainer.begin();
instead of
vector<int>::iterator it = stlContainer.begin();
You know, that’s about the first nearly practical thing you have mentioned. So if I write
auto i = {};
then it automatically initialises i to be the correct type and value, right?
Don’t be silly. Anyway, there is another use of auto I want to tell you about. You can use it to write functions the wrong way round.
Um…
Since time immemorial, curly brackets languages have let you make a function like this:
int someFunc() {
// function body...
}
But in C++0x you can write
auto someFunc() -> int {
// function body...
}
with the function’s return type supplied at the back of the function.
What? Why would I want to do that? That is completely mad. What is that, some politically correct adaptation of C++ for left-handed programmers or something? If I wanted to do that, I would code in Pascal.
It has many advantages. I believe it allows you to overcome C++’s most vexing parse. No, wait a moment, perhaps that’s the curly bracket initialisers.
I’ll give you a most vexing parse if you don’t look out. You are definitely deliberately winding me up now.
Absolutely not. There’s lots of other good stuff you must hear about.
You can stick in lambda functions anywhere you want, so that the appalling for_each template and its brethren suddenly become usable — as per my earlier petition — complete with a wonderful [square bracket] syntax for deciding which bits of local state will arise from the undead when the thing is called.
And you can make for loops in a style I last saw in CORAL 66, where one provides the list of values the loop variable takes. One, two, miss out three, five, six, now do four. And there are heaps of Boost library functions (of course), a scary new template programming concept called, um, ‘concepts’, a scary new template programming thing called ‘variadic templates’, constructors calling constructors, more fruitful unions…
You know, rather than bother you further, I think I will go read up on it for myself, if it’s all the same with you. Where can one find the dope on this?
Well, Bjarne Stroustrup’s site and the Wikipedia article aren’t bad places to start. Please shut the door on your way out. I want to concentrate on my new pet project. Nothing like the imminent arrival of a new C++ standard to encourage one to learn.
Erlang. ®
Regcast training : Hyper-V 3.0, VM high availability and disaster recovery
COMMENTS
Questioning the motives of C++ haters
Concepts, or concept checking, explicate the implicit interface of templates. They are a way of ameliorating the problem of templates producing terrible error messages when used incorrectly. Prominent C++ pundit Scott Meyers, well known in the C++ community as the author of the "Effective C++" series, has questioned the necessity of concept checking in the new standard.
The whole point of supporting initialiser lists (the { } syntax) is to allow classes, particularly containers such as std::vector to be initalised like arrays. i.e.:
std::vector<int> container = { 5, 6, 7, 8};
This previously wasn't possible.
References aren't pointless. They are safer than pointers, in that they cannot be null, must be initialised, and their value cannot be changed once initialised - They become an "alternative name" for the value, as oppose to some distinct construct that points to the value. This facilitates operator overloading, and simplifies code. If it wasn't for references, you'd have to de-reference the pointer returned by the operator:
my_class a, b;
...
my_class c = *(a + b); // returns a pointer that is de-referenced - defeats the purpose of operator overloading
As against:
my_class c = a + b; // exploits user's intuition of what + ought to mean
C++ certainly has more than its fair share of warts, but can we please see an article written by someone that understands the rationale behind the introduction of C++0x's new features?
I have plenty of criticism I could make of C++ in general, and C++0x in particular, but I feel most of C++'s defects can be attributed to historical reasons, or the fact that major sub parts don't gel together flawlessly. It seems to me that often the shrillness of the criticism you hear of it posted anonymously on the internet is in direct inverse proportion to the poster's actual knowledge of the subject - typically, they make sweeping remarks like "C++ is shit", or "C++ is to C as lung cancer is to lung", whatever that means. Why is it shit? If it is shit, how do you account for the fact that many major projects have successfully been completed in C++, among them GoogleFS, Photoshop, Firefox and openoffice.org - are the organisations that created those project just stupid? What would you write, say, photoshop in if you were starting from scratch? I suspect that these people's needs ( I suspect that they're web application developers and Java/C# developers that produce middle of the road business apps) are not best addressed by C++ in any case, but perhaps if they tried a modern C++ framework like Qt or WxWidgets they'd find that many of the oft-repeated put-downs are overstated, outdated, or just false (example: C++ is the only language that combines higher level abstractions with manual memory management, which is bad. Ever hear of RAII, or for that matter Ada?). Some of these same criticisms can be made of C (most prominently, things about the inherent dangers of native code), but people don't criticise C because Unix is C and Unix is cool and I'm a hacker. The difference with C++ is that you don't have to use C's low level constructs like char pointers for strings, or printf statements - there's always a much better, safer alternative.
A common, and valid, criticism of C++ is that it poorly encapsulates compilation units, necessitating recompiling client code when a class's definition is changed. That's the price you pay for the speed of having true local variables on the stack - the size of the class must be known in advance of compilation. The greater point illustrated by this example is that, essentially, C++ addresses the needs of a large (though largely reticent) group of people with a particular set of requirements that want the particular set of trade-offs that are least bad to them. Could there be, in principle, a language that better addresses *their* needs or preferences? Definitely. Is there one? For most of them, no. The number of people using C++ is not currently in decline (it was a few years ago), it just isn't growing as fast as the user base of other languages (source: Bjarne Stroustrup's website).
@Martin Usher - gross inaccuracies
"C++ started out life as an honest pre-processor for everyone's favorite systems programming language (which had accidentally slipped into role of applications language after PCs became common)."
Stroustrup's original compiler that partially implemented the language (as it existed then), cfront, created at Bell labs in 1983 was implemented as a preprocessor, back when C++ was known as "C with classes" and was considered highly academic. So what? The stated goal of Stroustrup from the beginning was that C++ was "designed to provide Simula’s facilities for program organization together with C’s efficiency and flexibility for systems programming." The suggestion that C++ "accidentally slipped into role of applications language after PCs became common" is preposterous - it became dominant because it popularised generic and object orientated programming for systems and application programming, and there wasn't anything better at the time. For many domains, there continues to be nothing better.
"I, too, try to push people at Python or other modern scripting languages for user programs."
I too code in Python, and think it's great. I think that it often makes sense to use RAD tools or scripting languages, especially given that they can be extended with C++ where necessary through the use of boost.python. Bram Cohen's original BitTorrent client was written (and refined) in Python, but the BitTorrent inc (formerly uTorrent) client is written in C++. Why? Because if it was written in Python, or even Java, it would be at a commercially disadvantage to other, faster clients that are written in C++, and users must have a python interpreter on their computer or a JVM. Sure, that performance difference is a feature that must be evaluated on its own merits just like every other feature, but it often still matters, as in this case. People talk about garbage collection
You are treating C++ as an extension to C, which betrays an ignorance on your part. If you really want to annoy a C++ person, use the term "C/C++". As I've already said in a previous post, C++ is much safer than C. It's quite possible to know C++ and not know C, because C forces the user to use dynamically allocated arrays, return codes, macros, extensive casting, weaker typing (when you use malloc in C++, it returns a void pointer. When you use new is C++, it returns a pointer of the requested type. If you use malloc in C++, you must explicitly cast the void pointer to the desired type), and does not provide safe abstractions like the standard containers, or allow you to create your own safe abstractions through idioms like RAII and language features like templates.
C++ haters often imagine that C++ code has mallocs haphazardly placed everywhere as with C, coupled with high level abstractions, which actually would be dangerous. C++ programmers know to use abstractions like the standard containers, and RAII to avoid "sullying their hands" (as I believe Scott Meyers put it) with explicit memory management wherever possible. This makes memory leaks extremely rare in practice, and makes the supposed panacea of garbage collection look unattractive.
Please can I have my Algol68 back?
C++ started out life as an honest pre-processor for everyone's favorite systems programming language (which had accidentally slipped into role of applications language after PCs became common). Its morphed into a monster. Its still possible to write decent code in it but for the most part when I see C++ I cringe -- its invariably pretentious spaghetti.
I, too, try to push people at Python or other modern scripting languages for user programs. Clean, portable and really difficult to screw up. For systems work C will do for the most part; you've got to know what you're doing at that level so just throwing source code at the problem and hoping the compiler knows what its doing (which is invariably not the case) won't work. C++ I just put up with -- you can't ague with its fanboyz, I can't be bothered playing specmanship pissing contests with them (I just know that there's lots of them, they're always late and their output is invariably buggy).
Flame away.....

IT infrastructure monitoring strategies
Agentless Backup is Not a Myth
Top 10 SIEM implementer’s checklist
Steps to Take Before Choosing a Business Continuity Partner
Enabling efficient data center monitoring