112 points · by dirtyaura · 12y ago · 212 comments
The complexity is there. Trying to understand the whole language at a language-lawyer level is mind-boggling. Trying to write libraries that make proper use of the goodies is very hard.
But using C++ isn't so bad, as long as you don't try to use every aspect of it. Just use the parts you need to be able to do what you're really trying to do. You don't have to pay for what you don't use. That's good enough for a huge number of programmers in a wide variety of contexts.
There's a lot of haters that can point out a huge number of flaws. But here's the thing: Most of them, I never run into. I don't care if the move syntax is confusing; I don't use it. Maybe I never will. If I have to, then I'll care about how good or bad the syntax is. In the meantime, the parts I actually use let me get my work done better than any alternatives.
It makes me uncomfortable not to have that level of understanding for a language that's so low-level and doesn't have the "Do What I Mean" bent of say Python. I'm "meh" on C++ going forward. I invested a lot of time into my copy of "The C++ Programming Language" (3d Ed.), for C++ 98, but I can't motivate myself to get the new edition and learn in the ins-and-outs of C++ 11. It doesn't seem worth it to me. I'm really hoping Rust catches on. It's a complex language in the same vein as C++, but the bang-for-buck in terms of expressiveness relative to complexity is better, I think.
* Streamlined language with carefully-chosen syntax and keywords (there aren't 10 different meanings for "static", for instance); entire concepts have been eliminated to no apparent ill effect in building real systems. Fewer cycles allocated to the language, more cycles allocated to problem domain.
* The 95% case for associative and sequential containers is built into the language, with (for me) enormous benefits to programming efficiency.
* A streamlined and carefully orthogonalized standard library optimized for systems programming. Golang has the best-designed standard library I've ever used.
* A ruthlessly pragmatic packaging and modularity system; unlike C++, packaging is not left up to the build system.
* Build-world compilation times measured in 100s of milliseconds rather than 10s of minutes.
If I was writing, say, a generic trie library that I was hoping to get hundreds of different programmers to use, C++ would be a tempting target because of generics. But it turns out, most of the time I build projects like that, I'm really just wanking. Another benefit of Golang is that it's so stripped down and pragmatic that it subtly discourages wanking.
A lot of people would add Golang's concurrency model (share by communicating instead of communicating by sharing) and lightweight threads to this list. I like Golang concurrency too but my sense of it is that among languages designed from the jump for concurrency, this isn't that much of a unique benefit.
I'll concede this point. I can't imagine learning modern C++ as a complete beginner, even if I know why the Committee overloaded keywords like this (or worse, at least to me, overloaded symbols): the general assumption that any good new keyword has already been used as a function or variable name in somebody's code, so that changing the meaning of that word would break their code.
We'll have to see whether the Golang designers follow in the C++ Committee's footsteps on this. I remember when Java was described as a clean and simple language. I would laugh at anyone who claimed modern Java was clean or simple: adding features to the language without breaking old code is a very difficult dance.
I started out as a C programmer, mostly coded embedded stuff, and have a decent knowledge of other programming languages (Java, Python, Perl, ...), but always avoided C++ for this reason.
When I made the move to C++, it was very painful to me. In C, I understood every aspect of the language, and going to C++ if felt like 'magic' happening all the time, and trying to understand every single aspect of the language was daunting. Every weird error was another tiring expedition into the language's core, the what and why. Fun is the last word I'd use to describe it, and I always ended up limiting myself to a very narrow subset of C++ because of this. At a certain point however you will be confronted with hairy ugly details of the language. Telling me that 'protected abstract virtual base pure virtual private destructor' is perfectly clear is living in your own small little world.
I enjoy coding in C, it feels like I'm in control, although you really have to do everything yourself, so it's a bit tedious. But C++? No, I absolutely don't enjoy 10-page error messages involving templates that have absolutely nothing to do with the actual error (although you have to give clang some credit here for providing a lot more helpful and compact error messages). It feels like you spend a lot of the time fighting the language and the compiler. Figuring out what a compiler error message exactly means can take a lot of time. And don't say this is the compiler's problem, it's the overly complicated language problem, parsing C++ is an absolute hell - which is the root of those amazingly bad error messages.
I said C++ goodbye about a year ago, and never looked back. My pretty recent discovery of golang was a breath of fresh air. Yes it's not suitable for embedded systems, yes it produces gigantic binaries due to debug symbols always being included and full static compilation (which also has advantages), yes there are no generics (...). It's not perfect, but the language is simple, using it is plain fun, you get a big standard library that even includes a real-world hardened web-server (Google uses it for it's download servers), and there is an amazing amount of 3rd party libraries available for such a young language. It feels a bit like a mix between a scripting and a compiled language - which is nice.
In fact I find the premise of all the Go/Rust/D advocates a bit strange. It makes sense to learn a tool that does something you can't do with your existing ones, but learning 5 tools that are mostly the same is a waste of time unless one is not into collecting tools as a hobby.
And how are Rust and Go "mostly the same"?
If none of these things matter to you, then they do seem similar. But if they do matter, then the difference is much larger.
I can understand that but keep in mind that C++11 is a completely different language to what it is C++98.
There is a lot of good stuff in the new versions of C++, but the language really could've used a bifurcation years ago.
That said, it's still the best tool in the toolbox for certain problems.
For me, I am constrained by the compilers that are used by my employers (VC10) so I can't use half of the new features (although I could use them in Xcode and macro them out I suppose).
assert(doappend_dwim([]) == ['a']) assert(doappend_dwim() == ['a']) assert(doappend_dwim() == ['a','a'])
The GOTO thing in PHP has almost been a non-issue all around, but highlighted the "don't use it if you don't like it" argument's flaws.
I also find that the ancient developer's design style and implementation left a lot to be desired, and if someone came across that as an introduction to a language, I think they would have hated the language too. That's why we should always write beautiful code and occasionally throw in obscure language features to force them to learn them :-)
Not to say tinkering is bad, its perfectly fine when trying to create the latest viral app or when learning how to do something. When engineering something, discipline is required.
And nothing stops any institution seriously committed to engineering to adopting practices that restrict language use to a subset (mandatory code review, static analysis tools that highlight deviant code and disallow it to be pushed, etc).
C++ most suited for demanding systems applications. [...] You choose C++ when the situation is already complicated.
... and then you have two problems </snark>. Yes, C++ has a lot of features, and those features are often individually useful to solve individual issues, but I remain unconvinced that this plethora of features and complexity pull their own weight.You can write useful, efficient software in languages that expose much less complexity to their users.
Re: complexity. Not having to understand C++ most of the time, or subsetting the language to have a manageable code base only works until you run into somebody else's code, or some 3rd party library. It's not a fix, it's a symptom of something broken.
But when you need to be able to precisely measure running torque or torque a fitting to known value, you can't avoid picking up the complexity of a torque wrench.
With that, I get the power without the rabbit hole.
I've used C++ over the years off-and-on (depending on what the clients required). You don't really need to use every 'exotic' feature in order to be productive. If you need something low-level with great compilers and a lot of great lib support, it's actually a nice language. All these new languages are nice, but Go and Rust just chisel off the 'ugly' in favor of some different 'ugly', IMO.
http://cpptruths.blogspot.co.uk/2006/08/g-compiler-option-we...
Make sure to get a guided tour. You can read all the stuff on the displays and in books, but you probably won't. So you'd lose all those nice stories about how the German ambassador protested the ship, because the figurines on the front symbolized the Roman emperors, with the Swedish king at the very front. Preposterous! The emperor of the Holy Roman Empire of the German Nation is the rightful successor to the Roman emperors, after all!
Pay attention to the fact that the Swedes weren't as stupid as people tend to assume. "Oh, they couldn't even build a ship that's floating!".
Yeah well, it was a design no-one had attempted before (bigger, three masts, two rows of cannons), the math to calculate the behaviour wasn't available, yet. And best of all -- contemporary analysis shows that they almost made it. Had the ship been just a little bit wider (I don't know, something like 20 centimeters or so?), it would have been fine.
Be amazed how the Swedes never just found a scapegoat to punish for the loss of their flagship.
Or just admire the architecture of the museum.
Whenever I'm in Stockholm I go there. It's inevitably a high point of my visits.
On the over-arming of ships going spectacularly wrong, see also the Mary Rose[1].
The natural language example of course being metaphor and allusion, I am thinking of practices such as indenting glVertex calls inside a glBegin/glEnd block, or overloading () on an object to convey the idea that "you should think of this as something like a function" when it is really not on a technical level.
Most such people are probably in the same position that I am in, and this is that they're using C++ primarily because they're involved in projects with a C++ legacy codebase. Language choice really isn't something that's up to individual developers.
But for personal projects, I've pretty much abandoned C++, other than when I need something to bootstrap on platforms that I can't make a whole lot of assumptions on, or when I have to operate close to the metal and C for some reason or another doesn't fit the bill.
The thing is that I don't really have a lot of beef with the language features of C++ (the way they're used in some libraries is a different issue). The features it has are generally there for a reason, and have good rationales. And C++ does pretty well in its chosen domain (system programming). It's not perfect (what programming language is?), but hardly terminally flawed, either.
But C++ simply doesn't meet my needs. It has a very strong bias for optimizing CPU cycles, even at the cost of developer cycles, but I'm far more likely to be short on the latter than the former. Those extra few percent of speed that I might gain (or might not -- some C++ features are not all that efficient, after all) are rarely worth adding even a few hours of development time.
That's such an overwhelmingly good reason to express yourself in English, instead of Esperanto, that you really don't need to postulate any additional reasons.
Most things like programming language choice follow heavy-tailed distributions, which means that there are a few that are overwhelmingly popular, as well as many that are extremely unpopular. The reasons that C++ turned out to be overwhelmingly popular may be mainly historical.
You could probably also blame popularity for making C++ so ornate. It jumped on every language trend over the years. Fortran didn't, but if Fortran had been popular...
The recent updates - C++11, C++14 and the drafts for C++17 are also very welcome.
When you need performant, deterministic, portable and testable code, you go for C++.
* only pay for what you use
* memory safety
* testability
* portability
(They even got a standard testing module.)
EDIT: How do you make lists with Hacker News markup?
Currently Rust doesn't outperform C++ partly because LLVM is optimized for the C subset (can't take advantage of extra aliasing/immutability information Rust has), but given that Apple is now betting on (quite similar) Swift I expect LLVM to rapidly improve in this area.
You just made one.
I guess C++ will do that to you. :)
Not that this is a bad thing.
I find straightforward, well-written C++ more comprehensible than Java and even Python (only due to Python's dynamic typing).
Of course, the definition behind straightforward, well-written C++ is very subjective.
auto y = std::move(x);
Is this good code? How do you review it? What's the type of y? Usually I would ask for at least one type statement per line. For example this seems ok to me, because the type is on the left. auto* x = new Foo();
But this doesn't seem ok: auto y = std::move(x); foo (A*x);
'A * x' creates a temporary with no documented type, but the conceit here is that we don't care. They could be ints, floats, matrices - any data type that implements '*'. By and large that is fine.Here you are just moving x to y. What is the type of y? the same type as x, which supposedly didn't cause you heartache throughout the rest of the function.
Stroustrup gave an interesting talk this year about how, everytime he introduced a new feature, people complained that it was not clear and asked for very verbose syntax. Instead of foo<T>, we get template<typename T> foo<T>(T, well, you get the idea. Now everyone is familar with templates and loath the verboseness.
Back to auto, it allows for 'generic' programming. Do you object to templated functions?
template<class T>
T add (T a, T b)
{
return a + b;
}
That seems really clear to me, as is the auto version: auto add (auto a, auto b)
{
return a + b;
}
If that is clear, why is auto x = a + b;
unclear? I can certainly come up with counterexamples where it isn't clear, but by and large I love auto, and use it all the time. (counterexample: we care about the type of x because we need to cast to a 16-bit int because it is going to be use to communicate with hardware).IMO you should still use auto there and use a static_cast<int16_t> on the RHS to make it clear to the reader that you're deliberately converting it.
foo(A * x) doesn't pose similar problem. On the other hand, if I write
auto bar = foo(A*x);
Then we can have the same problem (esp. if foo is a templated function).I wrung my hands when I started using 'auto' but none of the worries came to pass.
But yes, if the code is unreadable without a type, add a type. No biggie, and no one is suggesting inflexible application of rules (always use 'auto' if it is possible). The same way when I might call
foo(boo(x));
and it is not clear, I'll explicitly name the output of boo in a temporary variable: auto robot_velocity = boo(x);
auto robot_covariance = foo(robot_velocity);
And if that ain't enough, then sure, do this: robot::vector<float> robot_velocity = boo(x);
robot::matrix<float,float> robot_covariance = foo(robot_velocity);
I have to say, I find the last the most unreadable. I almost never care deeply about the type, and care deeply about the meaning.Interestingly, no one worries about typedef. typedefs wrapped around intricate collections (map of lists of dictionary of arrays) can effectively obscure what the underlying types are just as much as auto. But again, mouse hover, CTRL+I, or whatever your IDE supplies pretty much makes that a non-issue as well.
edit: the problem you are describing is due to too big a function, not 'auto'.
This is gun control applied to computer languages.
The solution is not to ban a useful feature that would ordinarily aid the understandability of code, the solution is to not abuse such features to write gibberish.
People can write spaghetti code with any syntax you provide them, even Python.
There should be no such thing as deep in a function, or at least not as deep as you mean (i.e. so deep that you can't figure out what y is): that would in all likelyhood mean your function is too long, has too much responsabilities. Good functions are short and composed of other short functions, they should be short enough so that you can read them through without ever having to wonder 'wtf is this?' I know this might sound like textbook stuff without practical use but it's simply the truth, as I learned through the years. In those years my functions only became shorter, and hence better named, and more reusable, and all code simpler to read. So auto was a godsend that didn't hurt once.
Personally, I avoided type inference in C# for a long time. But I never ran into a bug caused by type inference. While C#'s (and C++'s) type system isn't as advanced as Haskell's, if you screw up the types you generally get a compiler error. If "auto y = std::move(x)" compiles, then why do you care what type y is? You know it's the same type as x, and you can do anything with y that you could have done with x.
There's really nothing to fear.
vector<T> foo = ...
auto tmp = foo[0];
foo[0] = foo[1];
foo[1] = tmp;
When T is int, it swaps as expected. But when T is bool, instead of swapping, it copies the second item over the first, with nary a warning. And I'll wager you could stare at that code all day without spotting the bug.So yes, be afraid.
An updated version of ScopeGuard doesn't have this problem ( https://github.com/facebook/folly/blob/master/folly/ScopeGua... ).
So, yes, I'll concede that code that expects you to cast some kind of proxy type to a different type (e.g., the vector<bool> example, or the original ScopeGuard, or perhaps valarray) isn't ready for type inference. But that kind of code is pretty rare, so the list of exceptions to the rule should be short.
Besides, if you want to swap two elements, use std::swap.
I agree "auto y = std::move(x)" is (likely) poor coding practice. I only use "auto" basically as a shorthand (e.g. instead of writing "hand_crampingly_long_container_iterator_type v = std::fn(c.begin(), ....)).
I have mixed feelings about "polluting" the namespace with "useless" typedefs and similar aliases versus using "auto". The former leads to very explicit code, but lots of extra "overhead." On the other hand, "auto" is much more powerful than a convenient in-place alias as I've described, and I've rarely found myself in the position of looking at code and having to truly ponder over the type of an "auto" variable. On the other other hand, seeing a lot of either may indicate something else about the code and whether it ought to have a design review. It's (somewhat) subjective.
Unfortunately the slides are not online. But his presentation starts with a case of why 'auto' should often be preferred to explicit type declarations.
auto* x = new Foo();
Are you only referring to the fact that the type is noted at least once on that line? I ask because that would not pass my code review at all 99% of the time (manually allocating memory that way.)As for something like
auto x = std::move(y);
I couldn't say it is bad without seeing the context around it. Is it a small function? Is it obvious what y is? Looks fine to me in most cases.It's an odd mental leap for this old C hack, but it works quite well when you get into it. Bonus - no 'free' or 'delete' necessary.
auto x = std::make_unique<Foo>();
Unless you're implementing an allocation policy, you shouldn't be calling new and delete directly. auto it = std::find(vec.begin(), vec.end(), value); auto foo = *it;
... I would be sad.What if "it" were originally an unsigned int* but a refactoring changed that to a long*? Would you prefer the programmer hunt down all cases where "it" is dereferenced to change the type of the result, or would you prefer the programmer use "auto" to begin with?
auto gps_position = *saved_position;
I can think of cases where I'd want to see the type of auto, but not often.I think the STL may have been the worst thing to have happened to C++. It could have been so much nicer if something like Qt (the core part) was adopted instead.
If Qt is anything like wxWidgets, wxWidgets reuses the STL for its container types, basically providing a thin wrapper over the STL (or it can do with a build switch).
I myself find the STL very useful, so I am genuinely interested in which bits of the STL you wish were more Qt-like? Do you mean the GUI bits of it or something?
Qt doesn't reuse the STL container types, it provides its own - which I find much more pleasant to work with than their STL counterparts. The STL puts a lot of effort into providing types of flexibility that are irrelevant or useless to me (e.g. allocators) and doesn't provide lots of simple things that I need every day (e.g. an indexOf method for std::vector, a contains method for std::set, or a toUpper/toLower method for std::string).
Regarding iOS and Android, the attempts at getting C++ on them (particularly Android) are brave but I think for normal apps (not OpenGL or games), developers are probably better using Java. Like you, I too am writing for the Big 3 normal desktop OSes, with sporadic Android development and iOS tinkerings, necessitating learning new languages.
I think opinions on that greatly vary. I for one find a majority of what is in STL very well-designed and very usable.
But if you'll indulge me for a moment, consider how you'd convert a string to uppercase using the STL vs using Qt. The STL code (taken from http://en.cppreference.com/w/cpp/algorithm/transform) looks like this:
std::string tmp = s;
std::transform(tmp.begin(), tmp.end(), tmp.begin(), std::ptr_fun<int, int>(std::toupper));
return tmp;
Note the use of a temporary variable, because std::transform does a destructive update.The equivalent Qt code looks like:
return s.toUpper();
I'll let you draw your own conclusions.By the way if there's a simpler way to do that using the STL, I'd love to hear about it.
transform(begin(tmp), end(tmp), begin(tmp), [] (char c) { return toupper(c); });
...the only noisy parts are the calls to begin() and end(). On the other hand, it will work for any collection type with good iterators (vectors, lists, strings, deques, ropes, etc.).It is also trivial to write a mylib::transform_in_place() that cuts down on the noise with a one-line function.
from this single example I could say 'STL isn't bloated and contains just the things necessary while leaving plenty of room for extending. That is just the way it was designed' (And extending it is something I do regularly, resulting in a header-only library with tons of small helper functions containing something like noted in the other comments 'transform_inplace' and 'to_upper' which is implemented using the former. Also the resusability of most of these shouldn't be underestimated.) - but for this case I sort of agree that toUpper could have been a member of string becasue it's pretty basic and that if you work with strings regularly QString is nicer from the start as you don't need extra functions. But of course that opens the road to others saying that if toUpper is there, then why shouldn't x and y and z be there.. Never-ending :P. Which is also probably why the STL is the way it is.
* non templated tuples instead of struct: for example, 2 struct types are the same if the data types they hold is the same. Not sure if it's possible for statically typed language.
* tighter STL container integration with the core language syntax
* some way to do modules
* some new thing to make compiling much faster, so to avoid relying on precompiled headers. go and rust are so much faster for this, C++ is not. I still wonder if there could be some gcc or clang extension for this, it would be really appreciated. C++ is awesone to work with, but language implementations suffers from those little details.
C++ has std::tuple, but most people (myself included) find nominal typing easier to understand. I Would only use std::tuple in situations where I needed to store a values of the types of a variadic argument pack.
> * tighter STL container integration with the core language syntax
C++ actually does pretty well here, it has operator overloading as well as std::initializer_list.
> * some way to do modules
Hopefully a good modules proposal makes it for C++17
> * some new thing to make compiling much faster, so to avoid relying on precompiled headers. go and rust are so much faster for this, C++ is not. I still wonder if there could be some gcc or clang extension for this, it would be really appreciated. C++ is awesone to work with, but language implementations suffers from those little details.
Modules would help with compile speed. IMO, Go doesn't offer very many abstractions to the programmer that the compiler must eliminate so its easier to compile quickly. My 1 day experience with Rust was that it actually compiled quite slowly, do you have any personal experience with the language that you found it compiled quickly ?
(42, "foo", fun x -> x+3)
has type int * string * (int -> int)
in ML. It would probably be a serious extension to C++'s type system, though, and for limited benefit: you're asking for yet another way to do Cartesian product. Structs already do that. What's sorely lacking is sum types: type 'a option = Some of 'a
| None
type 'a list = Cons of 'a * 'a list
| Empty
---Integrating the STL at a syntax level gives a special status to the standard library, preventing users from writing effective replacements or analogies. Also, C++ has precious little orthogonality left, let's not destroy it.
---
What kind of modules are you talking about? C++ has compilation units, classes, and namespaces. What capability do you want that they don't already provide?
---
Good luck on the fast compilation front. That one will likely require removing things from the language, or making some major compatibility-breaking changes in the syntax (to make it easier and faster to parse), and possibly a rework of the template system. No. Way.
See http://clang.llvm.org/docs/Modules.html and http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n207....