Feeds

back to article An unthinking programmer's guide to the new C++

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 …

COMMENTS

This topic is closed for new posts.

Page:

Silver badge

@Greg Fleming

"Even C does not need to adhere too closely to the original K&R spec. Lots of weird so-called "illegal" code compiles just fine and dandy. Depends on what you're trying to do. That's kinda the point, y'see?"

Exactly. I code in most of the common languages, but C is my goto language[1]. I want to control the compiler, I don't want the compiler telling me what I can and can't do ... Especially when I'm writing close to the hardware (kernel/monitor stuff & device drivers). Before anyone asks, yes I still hand massage in assembler occasionally. I'm an old fart, remember?

[1] Pun intended.

0
0
Alien

Too much choice

I hate it when they keep adding new features to a language, I feel compelled that I must use them or else I will be left behind. I've only begrudgingly started using generics in C#, blah <lick out tongue> to nasty Lambda expressions.

As for C++, I gave up at copy constructors, thanks but no thanks, I'll stick to my lovely C.

Alien, as this is what C++ seems to be.

0
0
Silver badge
Flame

Operator Overloading == FAIL

Operator Overloading is a recipe for fail. Don't even go there. An operator should mean one thing, and one thing only.

In JavaScript, the "+" operator is overloaded. You think it means add numbers; but it can also mean concatenate strings, like the . operator in Perl and PHP. But JS, like Perl and PHP, doesn't distinguish between numbers and strings. So you can think you're incrementing a value; but if the interpreter thinks it was a string as opposed to a number, you end up multiplying it by ten and then incrementing it.

I have now resorted to subtracting negative numbers whenever I want to add, and concatenating an extra "" between strings.

And to those smug b******s among you who will inevitably say "It's not an issue with overloaded opewators, it's an issue with dynamic typing. If attempting to add a number and a stwing thwew an exception, thereby forcing you to perform explicit type-conversion, it wouldn't be a pwoblem" : you're half-right, but why the hell should I have to tell the computer what's a string and what's a number? It's a freaking computer and it ought to be able to work that out for itself, dammit.

0
0

@Greg Fleming

"Even C does not need to adhere too closely to the original K&R spec. Lots of weird so-called "illegal" code compiles just fine and dandy."

Do you mean the original- and now quite old- K&R C from the first edition of the K&R book? That was- while useful- at most a de facto standard and in practice there was still variation between versions of C. Hence (I assume) the need for the ANSI C89 standard, which most modern compilers are based on, and with which compatibility would be more important.

(Ironically, the second edition of K&R describes ANSI C89, not K&R C).

As far as the ANSI C89 standard goes, it depends what you consider "illegal" code. C89 tends to describe many things as "undefined"; i.e. you can do them, but it makes no guarantees as to what might happen if you do.

Your program might work as you expected; or it might work in a way that reflected your particular OS/compiler/computer architecture (i.e. it might give different results on another machine). Or it might crash on your machine.

Your compiler might- or might not- specify what such code would do and whether you could compile it; C89 itself wouldn't cover such matters though.

So it's quite possible that you could compile and run "illegal" C89 code- you just can't expect that to happen across every C89-compliant compiler.

0
0

Constant functions

Just to be constructive for once, I like the way you can make functions constant. Handy in embedded programming where you want minimal codesize and readability.

0
0

This post has been deleted by its author

Anonymous Coward

@ Michael Strorm

Precisely. The whole question of fitness for purpose does rather hinge on various compiler implementations more than the original or subsequently revised language specification.

The theory is that every compiler should strictly adhere to the latest standard for the language, but implementations do vary quite a lot.

Given that those who program in C tend to favour one compiler over another because _this_ will compile in _that_ while it won't in _other_ tends to reinforce that -- otherwise it would make any difference which compiler you chose. Clearly this is not really the case.

C (and derived) languages tend to be unforgiving in areas that don't matter where, perversely, they blithely allow the most freakish (but in terms of logic, completely valid) code to pass through anyway in really important places. I welcome rigidity but I also value versatility as well.

Remember that C and C++ can be totally dictated to by which headers I pop in -- I'm not _obliged_ to use the standard STDIO or any other headers, for example. C and its derivatives are designed to merely offer a high-level language abstraction for the native features of a given CPU architecture, nothing more. In this respect its pretty good and does what it does in quite a natural way.

0
0
Silver badge

Loops

The author says, "And you can make for loops in a style I last saw in CORAL 66" OK, I know it's supposed to be humour, but this is actually how loops are done in many (most?) modern scripting languages, such as Python . ( for i in [1,2,5,4] ) It's not a gimmick, it's the Right Thing. The list can also be an iterator (which is how you do the C-type loops, for i in range(1,10) ), and most importantly, instead of counting out an integer sequence and then de-referencing each element of an array or iterable structure, you just say "for x in array" . It's error-proof (of if it's calling the iterator method of an object behind the scenes, at least the right iteration thing is coded by the author of the object, not the user thereof, and debugged once and for ever).

Imitation may be the sincerest form of flattery, but I can't see the point of trying to do things in a compiled language that are natural only in an interpreted one. Write the high-level control stuff in Python (or Perl if you really must ... beauty versus the beast, but both work). Write the stuff that actually crunches data and needs to go fast in C. Scripting (interpreted) languages have huge advantages for rapid development and cool run-time tricks, and for the outer levels of the code, a threefold efficiency penalty is hardly ever significant. For inner levels where speed matters, vanilla C runs faster.

0
0
Happy

LOL Erlang

Funny 'coz I was having the same thoughts end of last year.

0
0
Silver badge

@A J Stiles

"but why the hell should I have to tell the computer what's a string and what's a number? It's a freaking computer and it ought to be able to work that out for itself, dammit."

<patience mode=on>

Because, AJ, computers can't think for themselves. You have to tell them what to do. Explicitly.

</patience>

0
0
Pirate

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

1
0

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

1
0
Flame

void *self, *referential; referential = self; self = referential;

In 30 years of programming, I have lost count of the number of languages I have used either commercially or for fun. The programming language choice, for the most part, is irrelevant. If the hard thing about you work day is the programming language and not the thing you are actually writing - maybe its time to find a new career path. Do you really find C 'hard'? Do you really find the notion of a pointer difficult to grasp? It seems peculiar to the programming community the amount of almost religious zeal they have for the tools they use. Do mechanics feel the same ways about their spanners? Do some mechanics refuse to use socket sets because they are a bit 'difficult' to understand? Are they really mechanics if they do?

In my many years of programming I haven't come across a single new language that can do something that C can't do or be made, quite trivially, to do. I am backed up by the fact that a lot of these new languages are written in C! In the end, programming is merely a syntactic reflection of how our brains solve a problem. Perhaps different problem solving approaches can be better represented with appropriate languages. But what's important is your ability to solve the problem and not which spanner you used to do it.

0
0
Bronze badge

@AC 08:28

I partly agree that the strength is in the programmer not the language but claiming it can all be done in C, trivially, is nutz.

So, a challenge!

Ignoring one vital aspect of readability (cos that's incompatible with what follows), write something small for me that exhibits use of

* OO, in the form of inheritance, virtual funcs etc. (the usual)

* multiple dispatch

* multithreading (that's easy, but...) *with* thread safety by use of totally immutable functions, and, because purely functional style programming generates garbage in immense quantities:

* garbage collection to pick up the dead pieces and recycle them.

All by hand. Preprocessor us is fine. Using a conservative GC like great circle etc. isn't allowed as 1) you didn't write it and 2) it won't work.

Whatever you do I can do it faster, better, more readably, more efficiently and just plain nicer in dylan (which I haven't touched for years, but anyway).

2nd thoughts: I don't know if OO as I'm familiar with it works with pure functional stuff (probably does but I've no experience with it), so let's split it into 2 and you can choose either: OO+MD or MT with immutability+GC. Makes it easier, surely.

Kettle's on, mate...

0
0
Stop

@ Blue Green from AC 08:28

OK - done it. I called it 'Java'.

0
0
Silver badge

@Blue Green & @AC 12:04

Blue Green wrote: "Whatever you do I can do it faster, better, more readably, more efficiently and just plain nicer in dylan (which I haven't touched for years, but anyway)."

Dylan? DYLAN??? The bastard child of Scheme/Lisp & ALGOL? I learned Dylan out of curiosity a little over 15 years ago, but never found a use for it ... in my mind it's a solution looking for a problem that probably doesn't exist. No doubt that's why Apple dropped it years ago.

AC: Good answer. Bad language, but good answer :-)

0
0
Bronze badge

@Jake

I wonder, does anyone read my posts before replying? AC said this: "In my many years of programming I haven't come across a single new language that can do something that C can't do or be made, quite trivially, to do." And hence my challenge -- in C. I'll repeat that, in C.

Now it may be that AC had written a working Java compiler/interpreter in C and was prepared to put that forward as a kind of DSL for my challenge, and I would have admitted he had won (overlooking that Java doesn't do multimethods), but otherwise I can't see how his answer fits anything I said and my challenge still stands.

As for your comments on Dylan, it was described by an expert as being a dialect of scheme. If you don't like it, do it in lisp (you have experience in lisp IIRC). I didn't mention this because I have no experience with lisp, whereas I do with Dylan.

I don't much like Dylan syntax, but Java is just terrible -- what kind of language requires you to write out the type of everything *in full*, without being able to denote a full type with a straightforward name -- it gets bloody awful with templates. In C++ at least you can typedef, in Java you can't and you can't even clean it up with a preprocessor because they removed it as cpp was 'abused' (translation: 10,000,000 numpty programmers didn't have a clue so they took it out).

When Java has closures (not the hack using anonymous classes), proper support for functional programming and a decent syntax (preferably extensible like Dylan with hygienic macros) then maybe you'll have a point.

0
0
Bronze badge

@jake again

A couple of examples of java syntactic crapness from a public tutorial:

CleanUp<IllegalAccessException,DisconnectTask> cleaner = new CleanUp<IllegalAccessException,DisconnectTask>();

-and-

Triple<? extends Collection<?>> q = new Triple<List<? extends Number>>();

The second is a bit contrived but not much. The first is quite viable. If they can't even get that right... FFS someone in the generics development team must have said *something* at the time...

0
0

SAPPEUR

Seems interesting, but only interesting at most. Saying reference counting is better than garbage collection is interesting, I wouldn't say that it's necessarily better, and presumably you'll still end up with the same problem of things going out of scope later if you don't scope properly (which is quite possible). I don't see the real advantage of this other than as far as order of destructors.

Integrity of pointers - yay!

Generics - why replace templates? Templates are fantastic.

Allocating on the stack - different how?

Multiple Inheritance - I find it annoying that you would remove a feature because people find it difficult to understand. You might as well remove complex maths in case people don't understand it.

Operator Overloading - syntactic sugar or not, if you understand it it's sensible and not misused. If you don't understand it you may well not get that it doesn't need to be misused.

Multithreading - yay! Does it work?

Safe casts - actually using C++ casts will not let you cast anything into anything, that's C-style casts.

Array bounds checking - cool, I guess I can get rid of those pesky vectors now (!?!?)

The problem is that it's limiting the language because some people don't use it properly. You know that it won't be taken up by the mainstream, and those same people will continue using C++ so that they can continue abusing it. The people who will suffer from using it will be the people that use the language well and sensibly and are limited by the 'safety net' that SAPPEUR provides.

0
0
E
Stop

Threads

[I don't care what language any of you like to code in. Doubtless I like some of them and can't stand others. Debating the identity of The One True Language is bootless.]

I've seen some stuff suggesting C++0.42x, if you will, is to have threads built in. Now here is something worth debating. Threads are AFAIK always operating system or virtual machine artifacts. Something like Java can have explicit thread support because it runs in a VM. C++ by contrast does not: it runs on the metal, and whatever thread model the metal & OS support can be exposed to C++ as a library (you know, posix threads, sun threads, linux threads, userland thread systems, etc). So adding explicit thread support to C++ seems pretty weird given that C++ does not define an execution environment.

If the idea is an abstraction wrapper that covers all possible threading systems, it is still a weird idea. One picks a thread system for it's characteristics: a wrapper just hides the details and specifics, makes it harder to use the thread system. Maybe a crappy comparison, but... did you ever program Windows GUIs with Win32 and then tried to move to MFC: what was fairly clean and reasonably sparse became opaque and baroque.

0
0
Boffin

Re: Operator Overloading

@A J Stiles:

overloading *should* be used to assist the user's intuition. So, a complex number class can use

a = b + c;

d = e * (b + c);

and not

a = b.addto( c );

d = e.multipliedby( b.addto( c ) );

which becomes a maelstrom of nastiness for even moderately complicated equations.

0
0
E
Happy

Clarifications, with apologies to M. Stob

Shamelessly nicked from an interview with Mr. Stroustrup.

1) Compare:

int i = {};

to:

vector greats = { "Newton", "Darwin", "Archimedes", "Bohr" };

2) Compare:

auto i = 0;

to:

for (auto p = v.begin(); p!=v.end(); ++p) cout << *p << '\n';

The auto says that the type of p is to be that of its initializer (v.begin())

---

My addition:

In the auto case you've already declared it somewhere. Presumably we will have to be a bit careful about saying 0.0 for double and 0.0f for float. Thus auto is not DWIM, as I first understood it to be. {} for an integral tyoe thus means 0, but for a non-integral type must present correct structure.

0
0
Silver badge

@BlueGreen & @E

BG: I can code in most common languages, if I must. My comments on Dylan are from memory, I haven't even looked at Dylan in over a decade. It's still the bastard child of Scheme/Lisp & ALGOL, all of which I've made a living with, regardless. That, and the fact that Apple dropped it like a hot rock because it was prretty much useless in the great scheme of things were my only real points.

Re-read my comment to AC vis-à-vis Java. I don't like Java. Never have, despite making a lot of money with it. I found AC's answer to be kind of amusing nonetheless.

E: [I agree with your preface. [Pardon this colophon, BG]]

0
0

Re: Threads

Just because it's specific to a library implementation doesn't make it wrong. Most of us don't choose threading models, we just use the one that the OS we're coding for lumbers us with, and all the threading support does is to standardise thread usage so that you don't have to worry about stupid different ways of doing it.

0
0

Same old C++:

... if you are shit, then you will write shit, but if you are _the_ shit, well, that's OK then. Someone up there wrote that they thought auto was like VB's variant 'type', and I suppose it can be used that way, but that's not why it was included.

My feeling is though that new features really confuse matters. Maybe I'm still at a _very_ educational stage of my development, but beyond C++'s complex inheritance, it oftens seems to me that C++ is a deliberate obfuscation of things you can do very reasonably in C.

C++ wants to be all things to certain kinds of programmer, but for most applications, C would actually be better, because its closer to assembly and therefore very controllable. Isn't control what C++ programmers crave?

0
0

Page:

This topic is closed for new posts.