253 points · by ingve · 9y ago · 132 comments
I like modern C++ because for me it's a reasonable compromise between java safety and C safety. Other than out of bounds memory accesses and legacy code I feel there is not much that can go wrong. However compiling C++ projects takes ages and in the projects I've worked on I often have to modify headers that are included almost everywhere. Every trivial changes requires a 5 minute rebuild.
After working with several high level programming languages with slow compilers I realised the following: typing is fast, compiling is slow. There is a reason why go is so popular. It offers that tradeoff in fast turn around time / compilation time with reasonably good performance and simplicity in exchange for more keyboard bashing and keyboard bashing is a cheap price to pay for what you're getting back.
I feel like C++ proves exactly that you can't.
Depends on what you mean. At a minimum, I think it's clear that C++ has avoided a Python 2/3 style split in the community. This means that otherwise relatively conservative users (I'm thinking of users on supercomputers in this case) are upgrading quickly to new C++ compilers and standard versions.
On the other hand, C++ has always been a kitchen sink sort of language, and it is even more so now. As codes age, they tend to grow and not shrink in the feature set they use, and so long-lived codes will probably never completely escape the demons of previous versions, regardless of how nice the shiny new features are.
1) are 90% every really large software projects written in C++. All the programs "everybody knows" just happen to be in C++. Examples include Chrome, Windows, Microsoft Office, Adobe tools, KDE, Autodesk, ...
Clearly those programs have massive scopes, large complexity, the need for extensive abstractions, the need for large teams cooperating, tests, ... all the stuff we value as programmers.
2) Are all programs in most other languages so ... small. In scope, in features, in ... Just look at Go programs on github. Or python ones.
Very large Python projects are a few 10's of thousands of lines of code. And they are limited by their complexity. Somehow C++ programs seem to have less of this problem.
Very large javascript projects don't even seem to get above a few thousand lines of code. And reading them, I can see why. Typescript at least seems to match Python in how much complexity it can contain without imposing too much of a burden, but that language doesn't match C++ either.
Most of those fancy languages are artificially limited in some ways. For instance, you cannot easily link QT into Go (nor can you do that with many other libraries, GTK has the same problem). C++ does not have that problem, and if it does, you can solve it. I do not claim doing so is easy, but it can be done. You're not stuck. Go on IOS ? It sort of works, with a boatload of limitations that make it utterly unworkable. C++ on IOS ? It works, with less limitations than Objective C.
I feel like C++ gets a much worse reputation than it deserves. Much worse. It is not the solution to everything, of course.
2) See answer above.
> I feel like C++ gets a much worse reputation than it deserves. Much worse. It is not the solution to everything, of course.
In the end it all boils down to Stroustrups quote about programming languages: 'There are only two kinds of languages: the ones people complain about and the ones nobody uses'
And then that gives you a huge historical inertia. Chrome started out using KDE's rendering engine, which was written in C++, at a time when writing cross-platform GUIs wasn't really feasible in anything else if you wanted it to also be reasonably fast.
And they stay in C++ because changing languages is a right pain in the whatsit, and C++'s ABI is so variable across platforms and compiler versions through history that integrating components in other languages is often not worth the effort to maintain. Not that it hasn't been done, of course, and done well. Look at how Firefox are now integrating Rust components in their C++ codebase - although they're doing it by relying on Rust's ability to expose a perfect C ABI, and C++'s ability to call it.
Point 2... yeah. I get this. C++ has a higher complexity bound than many languages, especially dynamic ones. C++ used as C++ rather than C-with-classes has a strong type checker and some very robust capabilities around memory management, program integrity, metaprogramming (even though the syntax is dire and the compile times are horrible). C++ expertise in large software construction is widely available. C++ will compile down to efficient machine code that runs well on many platforms. These are all huge advantages in large projects.
Python has its troubles with concurrency, and the lack of type information in the source code to help maintainers. Go is just too young - I suspect we're going to see some really giant Go projects emerging over the next ten years, especially outside the space you can see on GitHub. There will be big enterprises deploying enormous Go codebases, although they'll likely be made up of multiple components instead of one giant thing like we used to do. Rust's too young, Haskell's got the chops but is too weird for most people (and its own problems, although Stack has really helped with the developer experience), JavaScript is entirely unsuitable to a large maintainable codebase. I'd guess TypeScript can probably go a bit further then Python in that space, at least until Python's new type annotations start getting fully checked by tooling at which point it returns to parity (or exceeds it, due to not being JavaScript in disguise. Guess what, I don't like JavaScript, who'd've thought!)
But still we've got C++'s inertia to thank for a lot of this. It's huge, it's old, it's still being developed and still being used and there's a lot of knowledge and a lot of capability out there.
But then look at newer disciplines. Look at mobile apps - yes you can write C++, but the native languages of Android are Java and Kotlin, and of iOS are Objective-C and Swift. What are new developers going to want to do - learn Kotlin and Swift or figure out how to shim C++ into those platforms via the variously awkward methods available?
What about the web? How many web applications are written in C++? Very few, I suspect. It's all C#, Java, PHP, Node, Python and other modern things which may or may not be considered sexy.
C++ dominates in the older disciplines, the older software that's still here and we still use and will use for a very long time.
I think elsewhere it's being passed by, especially as we get languages like Rust and Go which are considered as possible replacements in the "I really need this to go as fast as possible" camp.
It's a shame really, as C++ is still a powerful, impressive language and the new stuff is fantastic. But I always felt when I was working as a C++ developer that I wished I could turn off those C-compatible core behaviours and completely block those implicit-but-dangerous type conversions, and get the compiler to scream at me about dangerous pointer usage (I believe something along those lines is in the works for a future standard).
And also a shame about D, which has its followers but has been largely ignored, overshadowed by C++ to start with and later passed by the new languages which get all the hype.
https://www.google.co.uk/amp/s/akrzemi1.wordpress.com/2013/1...
Adobe will never rewrite Photoshop in Rust or whatever. If you thought burying COBOL was hard.. C++ will outlast humanity.
I can already hear the Alien scientists: "An amazingly intricate and convoluted language for such a primitive species. The mismatch between their mental abilities and their language might explain the bug which caused the incident.."
Well, "adding more features" can't be done "simply" if you want to "maintain backwards compatibility"; indeed, in the process of doing this is that the "flaws" are potentially augmented.
Only if your program is trivial. That is, if you can afford to run it over and over with results you can verify in the output as being incorrect, sure, keyboard bashing works.
Most of us work on programs that have been made trivial by abstracting the complexity into a framework or protocol library - like a web server. You can keyboard bash out a correct rest implementation on top of a routing library in minutes.
The problem domain is tiny(but really flexible!), and largely automated by code generation in most languages. The programmer is only there to cross some t's and dot some i's.
It would be a waste of productivity to write your own http server from the ground up. Writing one is non -trivial. For every new programming language that wants to serve web apps, a webserver must be written in that language. Having a compiler that verifies or does more for you on a non-trivial program is great. Not saying c++ is the right language here, just that a statically compiled program with an expressive type system catches more errors at compile time. Some/(most) bugs are unapparent in localized, repeated runs and unit tests that really only ever test a small subset of the range of possible inputs.
I like easy as much as the next programmer, I just mourn the fact that we can't seem to provide a safe, simple and easy in the same programming language.
If only we could stop at single-threaded applications :-)
I'm not convinced modern C++ stops all issues with pointers/iterators and ownership either. But it's hard to tell because every large-enough application inevitable has to interface with legacy pointer code.
What it does do is make it easy to reason about how pointers are used across the application. Also worth noting that even with legacy libraries, you can wrap a given pointer with std::unique_ptr or std::shared_ptr and provide a custom deleter and maintain reasonable safety guarantees.
But I was considering modern C++ compared to, for example Rust. I'm not sure if the memory safety issue that Rust solves still exists as strongly with a purely modern C++ codebase...but then again I never run into those either.
For threads it's no contest between Rust and C++, although TSAN is pretty damn nice.
I think this problem started with templates - previously you wrote abstract base classes (interfaces) and concrete classes had most of the code changes. I avoided templates where possible largely because of this.
C++ compile times are a problem. Apparently there is a C++ interpreter[2]. Anyone have any experience with it?
[1] shameless plug: https://github.com/duneroadrunner/SaferCPlusPlus
https://stackoverflow.com/questions/38060436/what-are-the-ne...
https://stackoverflow.com/questions/38060436/what-are-the-ne...
Is anyone aware of a good tutorial or reference list for writing good modern C++ (C++11 or newer, I guess)?
My preferred reference for the language and standard library: http://en.cppreference.com/w/
The following is a longer guide on modern C++ style: https://github.com/isocpp/CppCoreGuidelines/blob/master/CppC...
And in case it helps, the main things I find myself using differently to C are:
- Smart pointers. If you're not using them, use them. They're amazing. Seriously. Never have to worry about freeing something ever again.
- Object oriented design.
- Const reference arguments.
- The occasional auto.
One word of warning though, there's a confusing similarly titled book called "C++ Primer Plus" which you should avoid at all costs.
Unfortunately, the book is C++11 only and correspondingly does not talk about C++14 or C++17.
Is there a reason to use C++ any more? Has anyone gone back and had good experience? I'd kinda like to but am wary of the old problems. (The other problem is that most interesting business logic is no longer in C++.)
Its a whole new language and much more stable when you just use smart pointers, take care of ownership and know how to use the right reference types.
If you were referring to Java/dotnet/python, well yeah. (I'm honestly curious to know what you meant).
Compared to PHP, Python, Ruby, C#, Java, JavaScript: true with some pedantic exceptions.
Compared to Haskell, oCaml: Usually true, unless facing both well-suited and well-tuned code.
Compared to small volumes of carefully crafted and profiled Fortran, C or Assembly: usually not true.
Compared to CUDA: Not true for applications well suited to GPUs. Still true for situations that map poorly to GPUs. Except CUDA is almost entirely C++! Recent CUDA compilers on recent GPUs handle C++ code directly very well. Nearly everything but exceptions and thread local storage is supported.
Now if the metric is startup time, that's a different story. (Though I believe there's been a lot of work on hybrid AOT/JIT since I left the world of managed languages, so maybe things are better now.)
Which is the #1 requirement for a bunch of applications. I can feel I want to go back...
Which means whoever wrote the code was doing it wrong. Which is not that strange given C++ really did (and still sort of does) make it easy to make certain mistakes. But which could be countered by a better understanding and learning of the pitfalls.
Good news is: all of that got in my opinion better since C++11 and beyond. Lots of cruft still there of course, but most of the time you don't need to touch it. And if you do have to, you're ither doing it wrong, or there's a really good reason for it. Should you start from scratch, using a proper book or tutorial, you shouldn't have too much problems. If you don't start from scratch, you're going to have to spend extra time in forgetting a bunch of things you learned about C++. I've seen more than a couple of programmers really struggling going from C to C++03 (and as a result writing C with a class here and there and, god forbid, even using a vector or string or algorithm), and from C++03 to C++17 is not that different.
Buffer overflows, now, those are a special pain in C and C++. In many applications you don't need to work with arrays directly, though; and when you do need to do a lot of stuff with arrays, you probably also need it to run fast.
None of your examples are a fault of the language - it is a fault of developer not doing necessary safety checks.
My own skills dont necessarily matter. If you're working on a project with 100 devs, it only took one bad piece of code (or a bad library) to bring the whole thing down - which is a main downside to the language.
The only major additional problem C and C++ bring to the table is that some bugs manifest as subtle memory corruption, so the cause of the crash isn't immediately obvious.
if (init; condition) {}
(Ref: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p030...). It just seems like clutter. I generally prefer when languages discourage side effects in a branch condition.
{
std::unique_ptr<T> x = foo();
if(x->something()) {
// use x
}
}
// x out of scope, destructed
becomes if(auto x = foo(); x->something()) {
// use x
}
// x out of scope, destructed
It's makes it easier to read the lifetime of x (an important thing you have to manually keep an eye on in C++ in many cases), and to determine what is in scope outside of the if statement. It's analogous to for-loops vs. doing loops "manually" with while. You're just used to for-loops by this point (if you don't like for loops then ok :).)C# is also getting (has got?) this feature.
In most languages, in most cases, scopes within a function are used to enhance readability rather than to specify program logic, so a feature like this would add more complexity than it removes.
It does improve readability. If you've ever had to have a series of conditionals in their own braces to keep the init variable in its own scope, then you have a use for this. The alternative might be having foo1, foo2, foo3… all in the same scope, and it's too easy to use the wrong one. This keeps things specifically constrained to the scope in which they are used, which improves safety and correctness, and I think also readability once you adapt to it.
Yes, it could be abused, but I don't think that's a reason not to use it for its intended purpose.
if (std::vector<int> v = f(); !v.empty()) { // Use v }
without requiring an extra compound statement to limit the scope and lifetime of v.
add_compile_options($<$<COMPILE_LANGUAGE:CXX>:-std=c++1z>)
with set (CMAKE_CXX_STANDARD 17)
Note: we had a green field application that started with an empty Emacs buffer so figured we could go straight to C++17. I doubt this is a particularly common case right now. struct S { int x1 : 2; volatile double y1; };
S f();
const auto [ x, y ] = f();
So it's just ordering based, I can't pull out one member by name? const auto x = f().x1; > const {a, b} = {a: 'hey', b: 'there'}
undefined
> a
'hey'
> b
'there'const auto [ x, y ] = make_tuple(1, 23);
I am, admittedly, not primarily a c++ dev though. Are structs typically ordered data structures in c++?
In C++ you have to, since it's guaranteed by the language that members are initialized in order of declaration (within the struct). And, like C of course, it also determines memory layout, padding and alignment
> Are structs typically ordered data structures in c++
Yes, and compilers like Clang even let you inspect their memory layout
Think for instance of a 2D point structure. There are tons of implementations, all with different naming conventions ; or sometimes storing them in an array. This allows to just do :
auto [x, y] = someRandomLibraryPoint();x will be an independent variable which will take the first value from the tuple, and y the second one.
I know it's not in C++17, will it be in C++20?
When will C++ finally catch up?
Anyway, Go goroutines and Python generators are very different beasts. Because the term "coroutine" can refer to very different things, implementing any single interpretation of the term would likely leave proponents of other interpretations disappointed. Coroutine support for C++ has been in progress for several years now, and some fundamental design questions have been quite controversial. However, there's now a Technical Specification out [0] and, if all goes well, it should be on track for inclusion in the C++20 standard.
[0] http://open-std.org/JTC1/SC22/WG21/docs/papers/2017/n4680.pd...
For that matter whole game is more than a little silly.
Boost.Fiber has Go-like channels[0] for example, and Boost.Coro has facilities for using coroutines like generators (by using Boost.Range)
[0] http://www.boost.org/doc/libs/1_65_1/libs/fiber/doc/html/fib...