A Tour of C++ (Third edition)
stroustrup.com
stroustrup.com
https://github.com/wcochran/closest-pairs/blob/main/closest-...
However, your code is full of vector accesses without bounds checking: vec[i] instead of vec.at(i).
That's just as "unsafe" as C, so I recommend not bragging about how far you've come.
Your code is full of what is essentially unprotected C-style
*(addr + i) = ...
... = *(addr + i)
You've been writing C++ since the 1980's, but your code is full of raw pointer math, and yet... "No worries about memory safety"?I have a feeling you'll be reaching for Valgrind or address sanitizer someday soon, just like the C programmers.
This safe, "no worries" C++ was segfaulting. You've managed to make it correct today but it's still unsafe.
Someday one of your coworkers is going to break it and this code will be trashing the heap. Mysterious memory corruption failures are your destiny.
That said, Happy Halloween!
> Someday one of your coworkers is going to break it and this code will be trashing the heap. Mysterious memory corruption failures are your destiny.
You could have written something like, "It's possible this code will break in the future and you won't even realize the cause, because it will appear as a mysterious memory corruption failure."
See how I left out a word like "destiny" and took out the whole bit about coworkers? Yeah, much nicer and less personalized.
The point was that being a C++ programmer is like being part of a horror movie.
I say that as a person who uses C++ in my day job. It's a nightmare.
You obviously have interesting things to say and opinion to share with a fair amount of passion, but the tone detracts from the message, which I find a pity.
We're getting so soft and so fragile, how does it end?
“Hard times create strong men, strong men create good times, good times create weak men, and weak men create hard times." (G. Michael Hopf)
but if you need a bit more speed you can still build with
-O2 -D_GLIBCXX_DEBUG=1 -D_GLIBCXX_DEBUG_PEDANTIC=1 # for libstdc++
-O2 -D_LIBCPP_DEBUG=1 # for libc++
/O2 /D_ITERATOR_DEBUG_LEVEL=1 # for msvc
this way you get compiler optimizations but the assertions are still thereI'm not even certain if using stl containers always use the heap.
I'm a bit confused at times, since I avoid using oop and inheritance, I prefer data oriented, I just write functions and avoid side effects as often as possible.
GCC is getting there thanks Red-Hat support.
Clang well, apparently all those compiler vendors that profit from it, see only a value in LLVM itself, after Apple and Google switched focus to their own languages.
- The important but half-baked features of C++20 that has never really been polished enough for actual production usage (modules, coroutines)
- Unnecessary "hyper-modern" C++ features which are dead on arrival (ranges)
- The dramatic increase in build times due to the STL library (which are accelerated by those hyper-modern C++ features) [2]
- The fleeing of LLVM/Clang engineers to other projects (as you've said, Apple engineers shifting work to Swift, and Google abandoning Clang and moving to Carbon).
- Implosions in the ISO committee (notably the controversy surrounding the rape convict)
It's really not looking good, but there aren't that much alternatives so I think people will just stick to C++17 for the moment. Listing the worthwhile competitors:
- Rust is a bit too awkward to use in many cases where C++ is used (particularly with unsafe Rust), and inherits some of the hyper-modern complexities/insanities of C++.
- Zig is still too unstable, they just finished reworking the compiler
- Jai is not even released to the public
- D might be a candidate but IMO they should really commit 100% fully for GC-less betterC mode...
- Nim still has many warts and unbaked features, and also there was a split in the compiler team [3]
[0] https://www.aristeia.com/TalkNotes/C++vstheVasa2-ups.pdf
[1] https://www.stroustrup.com/P0977-remember-the-vasa.pdf
[2] https://old.reddit.com/r/cpp/comments/o94gvz/what_happened_w...
Still, look at Fortran, Cobol, C, as examples of 50 - 60 old languages that aren't leaving us anytime soon.
What happens, is there is a steady descent in the number or people using it. I think it has started.
I know even C++ fanboys/lawyers, that are having a lot of trouble to keep up with all features from present and past... And 99% of developers I know, even very good ones, speak of "my 20% C++". So my feeing is 17 is the last version which some people can use 100% of.
While on the other hand I also have an issue keeping up with my 20% of JVM, CLR, V8, Azure, AWS,...
I guess things eventually implode and we need to start from scratch.
Imagine a group of teenager, getting interested into C++ via the Arduino or Pi based school projects, they search YouTube for tutorials (as common practice nowadays) and land on such tutorials.
Aren't you comparing it to C++23
We cannot say the same for Carbon.
Rust has a sensible model for language evolution, so its overly complex warts can be fixed over time. I do agree that unsafe Rust is not yet on par with the usability of C++ (given the huge pitfalls inherent in interfacing Safe and Unsafe Rust) but this is improving quickly.
Isn't unsafe usage very low in most Rust codebases, with maybe about ten of unsafe LoCs if any? Sounds weird someone would attack Rust based on unsafe.
Unsafe rust is not used often, they never argued that.
I think it's more of a spectrum than this makes it sound. For example, an unsafe function that takes a &[u8] argument can still assume that that argument isn't null, isn't dangling, etc. Just because a function is unsafe, or uses unsafe, doesn't mean other functions are allowed to feed it garbage. (Other unsafe code could do that, but that's per se UB, and the other code is unambiguously at fault.) All the "safe types" are still there in the mix, and the compiler is still catching the usual mistakes you make with the usual safe APIs, even in an unsafe block. (Though this has downsides as well as upsides, because there are more ways that producing garbage/invalid values with unsafe code can lead to UB.)
Unsafe Rust is harder to write than C++, or at very least, writing correct unsafe Rust is mandatory whereas it seems like C++ programmers are very sloppy and the same attitude will not deliver in unsafe Rust.
But the vast majority of software you're writing should be safe Rust, which is a much easier - the purpose of unsafe is to establish safe abstractions for your system and for a lot of use cases appropriate safe abstractions are already provided.
> Unnecessary "hyper-modern" C++ features which are dead on arrival (ranges)
Ranges is C++ catching up to where the rest of the world had already gone with ideas like "iterators" meanwhile. It's about as "hyper-modern" as the string_view or modules, both of which C++ was also very slow to get to.
* Google supposedly ditching from C++ to Carbon. Isn't Carbon some experimental initiative? i.e. wouldn't such a choice be considered in 5-10 years minimum, if ever? Has Google announced a move away from C++?
* The "controversy surrounding the rape convict"
As I understand it, P2137 was written to explicitly spell out the requirements so that there's an actual document saying C++ should prioritise safety and performance over compatibility, which WG21 voted against - making firm the fact that's not what C++ is about.
Left to its own devices, WG21 prefers ambiguity. This is infuriating if you need X, and you tell people "I need X, I can't get that from C++" and they will tell you "No, I'm sure you can have X, maybe the committee just doesn't understand your need" and wasting your time. It needed writing down on paper to ensure there's no room for that ambiguity.
Kate Gregory is one of the key Carbon people and if she had any "activities in clang" I'm not aware of them.
True for Kate Gregory, but not for many others.
* In the ISO C++ committee, people lose important votes all the time, again and again. Good features often take years before they gain enough support to be accepted. The committee - despite what the external perception might be - is actually quite hesitant and conservative, at least where it comes to affecting the behavior of existing code. In other words, there isn't such a thing as _the_ ABI vote, it's _an_ ABI vote. So it seems questionable that Google's whole C++ strategy would hinge on that one vote.
Additionally,
https://github.com/carbon-language/carbon-lang/blob/trunk/do...
A lot of these features are great and so they'll come in most compiles, maybe just not as fast as you want them. But the development happening for the PS2, PS3, PS4 and PS5, as well as windows and linux is massively different in the last 20 years. And it always seems like you're never going to get to use those new standards. And then one day they're just in your compiler and you are using them.
If clang doesn't keep up, people will stop using clang. Just like they starting using it and LLVM everywhere somewhere in 08-14 after it came out in 2007. It's both a huge switch (short time frame) and also natural for a product major release (long time frame).
If you have genuine data transformation tasks then I think ranges make a lot of sense. The kind of things that would be a 1-liner in Unix command line:
cat foo.txt | grep "bar" | cut -d "," -f 3 | sort | unique | wc -l
This can be expressed really nicely with ranges in a way that wasn't possible, or at least readable, before. If you want to use ranges to reimplement coroutines then of course it will be slow and ugly.As usual with new features, they shouldn't be used everywhere, even if they could. I do agree with the complaints on the massive size though - I feel it could be implemented quite simply if they only wanted 80% of the features.
Also, why isn't Microsoft in the "profit from Clang" list? Is Clang-CL not shipped in Visual Studio Installer? Did they find a way to compile Edge with VC++?
By the way, nice way of creating a throwaway account for the anti-ISO posts all over the place.
Just shows how distant the committee is from the developers.
Some console vendors are also depending on it as well (Sony, Nintendo). Clang really is the most important C++ project of all time, because it’s the only compiler that’s truly cross-platform (Windows, Mac, Linux, iOS, Android, game consoles, etc…) And recent failures in it catching up with C++20 should be very alarming.
Source?
Clang first should spend it's resources catching up with C++20, instead of spending them on C++23. The standard is yet to be fully finished.
Tell me again how much you care about C++20 when a library with a feature you want uses it but your toolchain doesn't support it.
It was even worse in the old Microsoft C++ days.
import std;
int main()
{
std::cout << "Hello, World!\n";
}
I even tried futzing with the latest compilers - VS 2022 Preview and clang++ 16.0.0 and it wouldn't work. Perhaps it works in some specific earlier released versions? As somebody noted, perhaps this book is for reading and not for actually trying out the code. Very strange for a programming language book in 2022.https://en.wikipedia.org/wiki/Input/output_(C%2B%2B)#Input/o...
Clang also requires some more command line flags to build modules it seems and g++ needs a command line flag to enable module support as well.
Microsoft's compiler seems to have the best language support in many areas, but seems to fail in others (notably the "core language features"). Then again, the standard isn't finished yet.
If I were to write a program in modern C++ I'd go for the Microsoft compiler. The open source and free implementations are clearly not capable of keeping up with a commercial software powerhouse when it comes to a complicated language like C++.
It will still be necessary to build the std.ixx source file (to produce std.ifc and std.obj for consumption; we will never ship prebuilt IFCs/OBJs for the standard modules). It takes maybe 3-5 seconds and doesn't need to be rebuilt until you change your compiler options or upgrade your toolset. Build system support for doing this automatically is a work in progress.
Although we have test coverage running that exercises every header of the Standard Library through `import std;`, we're still working on fixing various compiler bugs, especially in complicated scenarios (e.g. using Ranges through modules). My hope is that the experience will be solid by the time that VS 2022 17.5 is released for production.
If you had standard modules, then the import line at the top of that code does get you all of std, including std::cout and thus the I/O streams.
This example is still silly if you do have C++ 23 though because I/O streams are (say it quietly) basically obsolete in C++ 23 since it has a proper imperative print format feature like any modern language - with decent performance and all the format behaviour you're used to from other modern languages.
I expect that, when C++ 23 becomes a thing lots of people actually use, the canonical "Hello, world" example for it will use std::println()
What bothers me more is the lack of "return 0"
>5.1.2.2.3 Program termination [...] reaching the } that terminates the main function returns a value of 0.
And I just looked it up for C. Since C99, if the return type of `main` is `int` and there is no explicit return (or again you fall through to the end without hitting one) there's an implicit `return 0`. Before C99, undefined.
A return statement in main has the effect of leaving the main function (destroying any objects with automatic storage duration) and calling std::exit with the return value as the argument. If control reaches the end of main without encountering a return statement, the effect is that of executing
return 0;
In 2023, compilers are likely to support this - and you will have a less-obsolete book. If Bjarne had written a C++20-only book, it would have been supported by existing compilers, but would have gotten older, quicker.
Not yet. Most of the C++ 20 features are implemented in at least one compiler, but if you just write a whole pile of C++ 20 without checking all the features you used are in all the compilers you use, that won't work.
Open source compilers (Clang, g++) lack more features.
MSVC's development seems focused mostly on ticking off boxes, whereas GCC is focused on actually implementing things properly and not releasing things until they actually work. Clang is all but abandoned.
There are also experimental flags to enable (some parts of) this behaviour on the most recent compilers, apparently. (i.e. https://learn.microsoft.com/en-us/cpp/cpp/modules-cpp?view=m...)
Clang doesn't seem to support modules well and g++ is rapidly falling behind the other compilers. It'll be a few years before this code will compile on any system of your choosing. I'm confident Microsoft can release a compiler that will compile all the code mentioned once C++23 gets standardised, though.
Kind of weird to write a book using a language standard that's not even out yet, especially in a language where the freely available compilers lack a significant portion of the standard, but as one of the language's designers I can see why he's getting ahead of himself.
It's probably better to have this book available already once C++23 does finally land than to have to wait for standardisation before writing a book using it, but I think the book shouldn't have relied on unreleased standards or custom setups like it does until the new standard is out. Yes, you can get a std module of your own and yes the performance improvements are significant, but with open toolsets lagging behind I don't think it's smart to merely mention the downsides in a side note and the appendix.
[0] https://learn.microsoft.com/en-us/cpp/cpp/modules-cpp?view=m...
$ /usr/local/Cellar/llvm/15.0.3/bin/clang++ -fmodules -std=c++2b hello.cpp
$ ./a.out
Hello, World!Sure, the compilers might be a little bit behind, but who cares, I believe it's just a matter of time before they implement the missing features. They are pretty solid, the libs are battle tested, the ecosystem is huge (which can be an issue too).
For me the bigges issues are:
- lots of pre-11 docs and blogs showing up in the first 1-2 search pages
- not clear answers or FAQs about how to develop cross platform code (and backward compatible), the devil is always in the details here.
- not always clear which tool to use: what do I use for unit tests? And coverage? I would like to have like 2-3 top used libs, the rest I don't care
- some things which should be basic in 2022 can be daunting for people coming from simpler languages like Python or Javs, stupid example: dates. I see that with c++20 they did a lot of good work (with chrono, not sure if there is anything else), but that's not enough. The API is really good, but it's quite minimalistic for a 2020 standard. You can clearly live with that, but if you want to keep the language competitive you need to provide also higher level constructs. (Just to say some BS: Take Python's date module and copy it as is.)
Finally, if you exclude all the features you won't probably ever use, focus on simplicity and use the tools at your disposal (clang-tidy, clang-format, etc.) I think things are quite OK. But hey, I am not paid to work on old c++ codebases so of course I might be biased :)
Like LLVM and GCC contributions, GPGPU frameworks and Khronos standards, language runtimes,...
This is good too: https://github.com/isocpp/CppCoreGuidelines
I also liked Scott Meyer's book "Effective Modern C++".
Some other books on this front,
"Beautiful C++: 30 Core Guidelines for Writing Clean, Safe, and Fast Code"
https://www.amazon.com/-/en/dp/0137647840
"Embracing Modern C++ Safely"
https://www.amazon.com/dp/0137380356
Also with clion and Visual Studio, it is possible to write code while having the static analysers ping back into the core guidelines.
C-- and Orthodox C++ are there for a reason. People in the committee and Bjarne himself don’t write any production code, so anything they say, do, and standardize is taken with a ton of salt, often with sarcastic comments. It’s been years since anyone I know actually welcomed a new feature in the language.
I don’t even understand where outlandish features like ranges are coming from. These don’t solve ANY of the real-world problems, so why even invent this when you can fix outstanding issues instead?
https://ptgmedia.pearsoncmg.com/images/9780136816485/samplep...
It's worth comparing that to one of the more popular free C++ resources, learncpp:
https://www.learncpp.com/cpp-tutorial/container-classes/
The 'advice' section in the Tour excerpt is perhaps the most useful part. The learncpp excerpt is more about writing your own container class - note that many would consider the examples outdated with lots of raw new and deletes, but others would say, how else would you learn why uniq_ptr was introduced? (learncpp covers that later).
As far as how containers are allocated, C has malloc, calloc and free; new and delete in 'C with classes C++' are wrappers around those functions, and modern C++ has unique and shared pointers as wrappers around new and delete in turn. Actually learning modern C++ in depth thus seems to require going through that whole chain, including gaining a solid understanding of stack vs. heap, and the benefit is improved performance relative to languages like Python and JavaScript.
There's a notion that one can prototype in Python and then just translate that easily to modern C++, using idioms like ranges, without necessarily knowing the history of C++. It's an interesting idea, seems to be fairly popular, but I'd guess you'd still need to have that foundation in C to make it really work well.
That was my first thought on looking at the github link posted by waynecochran above: if I'm going to write C++ code that looks like that, why don't I just use Python or a similar language? What exactly is C++ doing for Wayne here?
It's not going to be much slower if it all, given that all he's doing is invoking higher-level abstractions.
Another thought: again, given the abstractions and high-level resources that C++ programmers will be coming to rely on in the years ahead, someone could "just" write a back end that translates a cleaner high-level language like Python to modern C++ for compilation and optimization.
Apparently that Python translator is still to happen, given how many keep using native libraries written in C, C++ and Fortran.
And cython isn't that great, given that it requires manual tuning.
As someone who wants to follow the same trajectory, how did you do it? And how did you dissociate professionally from being seen as the C++/systems guy?
I still consider myself a systems programmer mostly writing glue code in Go/Python and jumping into C/C++ as required to improve performance when required.
For C++20:
* Ranges! With may range operations and views
* Expansion of ability of compile-time computation, including a lot of standard library code.
* Concepts - constrained templates
* 3-way comparisons with spaceship operator + automatic comparisons generation.
* You can write your own modules (Java-esque import rather than textual inclusion)
* Support (albeit ugly) for co-routines
* Spans: https://stackoverflow.com/q/45723819/1593077
* Parallelism primitives
* Asynchronous network operations in the standard library (Boost-ASIO-based IIANM)
* Can safely implement scope guards
For C++23:
* Standard library via modules
* Stack traces (e.g. in exceptions)
* Many range views/algroithms/adapters
* Expected: https://stackoverflow.com/q/68368581/1593077
* Monadic semantics for std::optional
* etc.
> Are there really new features promised that today's programmer simply can't live without
Well, people can live with a lot. Many people write C, after all... so you could ask that about any language undergoing long term development.
Can you elaborate on this?
YouTube video about scope guard: https://www.youtube.com/watch?v=WjTrfoiB0MQ
Description of the change to the standard: https://isocpp.org/files/papers/N4152.pdf
Currently I use C++/17, have to rely on compiler-specific intrinsics. They work fine in practice, but standard library functions are IMO better.