Hacker News new | past | comments | ask | show | jobs | submit login
A Tour of C++ (Third edition) (stroustrup.com)
224 points by codewiz on Oct 30, 2022 | hide | past | favorite | 146 comments



I’ve been writing C++ code since it’s inception in the 1980’s. In the last two weeks I’ve written close to 1000 lines and no raw ptrs… in fact no smart ptrs either… not even one c-style array. No worries about leaks or memory safety. It doesn’t look anything like C++ code I wrote even 10 years ago.


I'm curious and would love to take a look. Any chance any of that code is available somewhere? My c++, little that I write, mostly looks like C and I'd love to learn something new.


Most of its in a private GitHub repo but I think I can open a piece of it… here is part of it ... a header only library for computing closest pairs...

https://github.com/wcochran/closest-pairs/blob/main/closest-...


Why is Eigen/Dense included if you never refer to anything Eigen and just take it as a duck-typed template parameter?


True.. good eye .. the operations on type P are very Eigen specific, but another type could easily provide those.


Much appreciated, thank you!


After giving your code a quick skim, I cannot see any mistakes in your vector indexing.

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.


Uh no, vec[i] may be unprotected in release mode but all three major standard library implementations, MS STL, libc++ and libstdc++ have bound checking in debug mode (along with many other sanity assertions, such as correct sorting predicates, etc) ; this way you get the (horrendous) bound-checked cost when developing and can ensure decent performance in release.


Who really uses debug builds in modern C++? They are just too slow to be usable.


I do as far as is possible all of my development under my stdlib's debug mode with -fsanitize=address and -fsanitize=undefined. If it's slow like this on my 2018 workstation, it'll be slow in release mode on my users's 2011 dual core laptops and on raspberry pis.

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 there


I always use debug builds while testing. They are of course much slower, but far from unusable - and I am mostly writing audio code


Plenty of people, not everyone is doing AAA at 120 FPS.


Debug doesn't have to mean unoptimized.


I do! How do you use a debugger otherwise?


A) I do B) plenty of “debug” checks can be enabled in a “release” build, e.g. just don’t define NDEBUG


They compile a lot faster.


You could have raised any of those technical poitns without coming off as an asshole.


Well, there is always a option to enable bounds checking in operator[](), all major compilers provide defines or compiler switches for that, and I would advise anyone that cannot prove otherwise via a profiler to do just that.


Not bragging at all.. it was just introspection on how different my code looks now… maybe I should find some older code that is fraught was dangerous constructs. In fact, early versions of this were segfaulting for the very reasons you mention.


Thank you for being honest.

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!


Your comments come across as pretty mean-spirited. Let me rewrite one line for you. You wrote:

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


And then I said "Happy Halloween".

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.


The point of the post by my fellow HN person was to give you feedback on your communication style.

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.


Why are people so delicate today?

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)


It’s not about people being delicate, its about what you value more: saying whatever you feel like saying, or actually getting your point across. The more inflammatory your tone, the less likely it is that you’ll change anyone’s mind, because they’ll be more likely to dismiss outright whatever you’re saying.


This quote doesn’t exactly make you look like the badass you think you are.. and all over C++ array access. Does that sound like a topic that warrants escalation to confrontational language to you?


I have a love/hate relationship with C++ ... probably like most C++ programers.


I have no love for C++.


The most dangerous thing I do is index a `std::vector` for which I can add range checking -- which I only do when debugging -- I am not willing to pay for that at release time. I am not performing any address math that can not be statically or else dynamically checked. No explicit memory allocation anywhere -- C++ does all the memory management for me. This is not true of older code I have written.


To me the code looks like very reasonable c++, and quite modern. I suspect the comment about memory safety may have been related to leaning heavily on things like iota, copy, partial_sort, lower_bound, etc as opposed to doing those things “by hand”.


I think it's much better to double-check your i's than to use `vector.at(i)`. Being unchecked at runtime is the benefit.


A project that my team works on might give you an impression: https://github.com/arbor-sim/arbor


That is some hard core science simulation...


Most Google C++ code is written like that, check out their repos on GitHub


If you consider thread safety an aspect of memory safety, I still see those issues pop up in modern c++. And memory leaks in terms of ever growing maps still happen. But the only times I have seen use after free or similar in modern code is where there was a bit that wasn't so modern. Is there some list for clang tidy modernize that will treat using anything other than value semantics as a warning?


He's just talking about using std::vector everywhere.


But std::vector has been around since C++98 (and in the STL even before then). What's changed?


A lot. Reading Scott Meyer’s Effective Modern C++ makes me realize how different things are. Just providing a type doesn’t do it… it’s the whole ecosystem around it.


it was such a PITA to use in 1998 ...


That and several other std types + algorithms…


I was called inexperienced because I was saying pointers are not 100% necessary in C++ anymore.

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


What are the new language features that let you avoid using smart pointers?


I feel like the standards are starting to get ahead of implementation. It's almost 2023 and C++20 still doesn't have even full support in any of the main compilers.


VC++ is mostly crossing the finish line already.

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.


There's a looming feeling that C++17 is really going to be the last version of C++ (practically, in production). The Vasa is now half-sunk [0][1], but the alternatives are yet to be truly born. The current issues surrounding the language standards:

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

[3] https://github.com/nim-works/nimskull


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

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.


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

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.


Depends on the use case, and how deep into abstractions you're counting. Unsafe is very common in embedded (which is IMO one of the prime use cases for Rust), since you're doing reg writes, interacting with DMA etc.


That’s not an attack. I think they are just trying to make the point that once you enter unsafe rust, you can use any unsafe language since the biggest benefit of rust is gone.

Unsafe rust is not used often, they never argued that.


> since the biggest benefit of rust is gone

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


Can you elaborate regarding:

* 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"


The main Carbon contributors are those that ramped down their activities in clang after Google lost the ABI vote, so they decided to create their own toy away from ISO processes.


It's not so much about "the ABI vote", it's the larger direction summarised in P2137 ("Goals and priorities for C++"")

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.


And in Rust one needs to write a RFC, and also not without going through endless discussion threads until a moderator locks them, in some more hot topics.

True for Kate Gregory, but not for many others.


* Where do we know about this ramp-down from?

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


It has come a few times on Reddit discussions complaing about clang slowdown.

Additionally,

https://github.com/carbon-language/carbon-lang/blob/trunk/do...


I share the feeling, however I would point out C++23 as the last version, I think the ecosystem will still make it that far, afterwards is as you point out.

Still, look at Fortran, Cobol, C, as examples of 50 - 60 old languages that aren't leaving us anytime soon.


The languages do not die in one day. In 30 years, maybe there are some people writing new code in C++38... and of course the immense code base already existing will stay for decades.

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.


Not wanting to do public shaming, there are still tutorials being uploaded to YouTube using Turbo C++ for MS-DOS.

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.


Those Turbo C++ tutorials tend to come out of India, and it’s because their schools are stuck teaching that. But those aren’t really tutorials for modern C++, they’re tutorials for C-with-classes at best.


Definitely, however many beginners don't know about it.

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.


That's not an hypothetical btw, I had students in France who fell into this


I was doing game dev in 2010-2013, and we had very partial support for C++11 features, depending on which platform we were on (playstation vs windows). We had fear that C++11 features would never be there, then saw the proposals for 2017 and were like "well that will NEVER happen"... Then the PS4 came out with good 2011 support and I think making progress on 2017. I believe the studio is full on 2017 support now. They're always purposefully 5 years behind so they don't fight insidious compiler bugs.

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


I've been using c++20 in prod for a few years with concepts and coroutines and consteval from the things I have off my head, and things work fine in msvc/GCC/clang, what even are you talking about?


Ranges is spotty on clang and source_location is inconsistent between compilers, off the top of my head.


Spotty is an understatement, concepts and coroutines are still very buggy and inconsistent between compilers as well. GCC and MSVC released an initial version of concepts two years ago that was far from complete. It's much better today but still no implementation is remotely good enough for production apart from some limited aspects.


100% agree with this. There's nothing in the new standards past 17 that actually helps me in real life day to day work. Most of the new features are solely for code-golfers (see ranges). Mean while co-routines and other concurrency extensions have languished for years as TSs with only partial support. Here's the full list of TSs [1], half of which only have partial or no support despite being 5+ years old.

[1] https://en.cppreference.com/w/cpp/experimental


Ranges is one of the few things in 20 that I really like - not having to do begin()/end() madness for stuff like sort, transform etc means you aren't thinking about the _how_ and can spend more time focusing on the _why_. It starts to feel like Unix command line with pipes, finally I can chain together the components I want without making tons of unreadable of intermediaries, and potentially without even any allocations if I play my cards right. I can also safely do transforms on vectors where intermediaries would require lots of memory, which would have meant "one big stonking for-loop" before. Ranges are amazing and I'm really annoyed clang is dragging its heels with proper support.


It’s all fun and games until you actually use it in a non-trivial scale and you experience compilation times go through the roof. (Your Debug builds will also be really slow.) It’s just not a good feature to use in the current state of C++.

https://aras-p.info/blog/2018/12/28/Modern-C-Lamentations/


Interesting read. It seems to me here that they're trying to shoehorn ranges into coroutines though - yes it technically works, but it's not pretty or performant.

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.


Just wanted to add that the linked piece is a really well articulated criticism of c++. I say that as someone who has been using c++ for about 30 years.


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

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.


Was wondering what other competitors does C++ has beyond Rust and Zig, thank you for the list and detailed opinion


also carbon, which is brand new.


Well, yeah. The reason I didn’t include Carbon in this list is because even the first draft isn’t complete right now.


> even the first draft isn’t complete right now.

Aren't you comparing it to C++23


Even if incomplete, one can produce actual binaries that use C++23 features.

We cannot say the same for Carbon.


I don't know what motivate you to keep repeating this narrative, Clang currently have good support of C++23 while MSVC have none[1], if your emphasis is on the standard library side, Clang is the only one that is compatible to all three major implementations and do use libstdc++ and MS STL on their respective "main" platforms.

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++?

https://en.cppreference.com/w/cpp/compiler_support/23


I am not the only one, this is a common discussion point on C++ communities.

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.


Who exactly cares about C++20? Most (mis)features of the “standard” won’t be used for years anyway, until the codegen stabilizes and performance impact will be known. Most of people in these communities never got a dollar for a line of C++, and people who did rarely express their opinion (but you can still find it online if you try)


It seems pretty obvious to me that you never lived through the bad old days when compilers all did whatever they wanted.

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.


Good to mention Microsoft is also depending on Clang for a lot of things (Microsoft is also quietly pushing devs to use Clang-Cl, as MSVC has really showed its age and is still notorious for bad error messages and subpar compiler optimizations…)

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.


Where? MSVC is not going anywhere and has been partially rewritten.


> Microsoft is also quietly pushing devs to use Clang-Cl

Source?


Have you tried using ranges with latest clang? That's a pretty central part of C++20 and it doesn't work.


> Ranges [are] pretty central part of C++20

Just shows how distant the committee is from the developers.


Have you tried converting iterations to SIMD and using vector extension to target x86, ARM, Webassembly and compile for Linux/Windows/MacOS with a simple piece of code? It's a pretty significant speed up and it only work with Clang.


What does that have to do with standards support?


None of that is part of ISO C++ compliance.


How is ISO C++ compliance relevant to actual development?


For many places it is quite relevant when choosing official compiler toolchains.

By the way, nice way of creating a throwaway account for the anti-ISO posts all over the place.


The ABI vote was C++ being effectively assassinated with a tombstone on top. What a horrible decision to effectively end a powerful and long-standing programming language. Words cannot convey how angry I am that a self-obsessed committee killed the language with a decision of the highest, absolute idiocy.


There are even c++17 features of the standard library that are incomplete in some major implementations like libc++


What do you mean? It has ALWAYS been like this.

It was even worse in the old Microsoft C++ days.


Microsoft C++ is leading the green boxes on C++20 compliance.

https://en.cppreference.com/w/cpp/compiler_support/20


The boxes may be green but just two weeks ago I had to report two msvc bugs, one against if constexpr and one against requires-expression, which breaks very simple language examples. In practice it's much buggier than GCC (second least buggier) and Clang (by far the least buggy, I think I only ever reported a couple of core bugs to clang versus maybe 30+ for MSVC even though Clang is my main compiler and I use MSVC only for testing)


Related link: The Definitive C++ Book Guide https://stackoverflow.com/questions/388242/the-definitive-c-...


To focus on the book itself, the very first "hello world" example doesn't seem to work with any compiler. Literally

  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.


He says in the book (right after introducing that example), "if you have trouble with import std;, try the old-fashioned and conventional #include <iostream> ..." And he shows a snippet with that.


The title says it covers C++20 with some C++23 features. This requires a module version of the standard library's iostreams mechanism - and that's a C++23 feature.

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.


> If Bjarne had written a C++20-only book, it would have been supported by existing compilers

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.


Looking at this table: https://en.cppreference.com/w/cpp/compiler_support it seems like you should be able to use almost all of C++20 with a recent Microsoft compiler without issues.

Open source compilers (Clang, g++) lack more features.


Ooooooh not at all. MSVC does "support" most features but they are full of issues.

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.


Fair, last time I looked at that table there were still holes for MSVC but they're apparently done.


More out of curiosity, I tried with a newer llvm from home-brew on Mac and it worked.

    $ /usr/local/Cellar/llvm/15.0.3/bin/clang++ -fmodules -std=c++2b hello.cpp 
    $ ./a.out
    Hello, World!


Modular standard library is part of C++23, unlike the modules themselves which appeared in C++20. In Visual C++ you'd need to install modules for the standard library and use /experimental:module and /std:c++latest[0]. Also half a year ago I had to use import std.core; instead of import std;

[0] https://learn.microsoft.com/en-us/cpp/cpp/modules-cpp?view=m...


The author later states that std as a module isn't implemented in standard C++20 (though hopefully will be in C++23) and provides ways to work around that somewhere in the back of the book. It's somewhere in the appendix.

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.


The keyword "import" should clue you into why, which I'm guessing the book explains at some point earlier. You need to enable C++ modules.



The point is the code they cited is relying on a C++ 23 feature (standard modules) which isn't yet ratified (hence the name C++ 23) and nobody yet completely implements.

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()


No, this is about modules. See first line and this is verbatim from the book.


You're right. Apparently, it's supported only by MSVC at the moment (Standard Library Modules): https://en.cppreference.com/w/cpp/compiler_support

https://github.com/microsoft/STL/pull/3108


Yep, that's my pull request. :-) At the moment, it's usable if you build the microsoft/STL repo with VS 2022 17.4 Preview 3 or later. When VS 2022 17.5 Preview 1 ships (in the very near future; can't say when exactly), it will be "in box" without the need to build our GitHub repo.

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.


Other compilers support modules in varying ways as well, but there's no universal module "std" yet.

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 should work for g++, as long as you build you own "std" module (which sadly is somewhat complicated) and enables -fmodule-ts. I guess he's hoping that will be easier in 2023.

What bothers me more is the lack of "return 0"


C++ standard 3.6.2[5] since like forever...

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;


Omitting return is allowed in main.


On Linux/Unix you will get in a (somewhat) random exit value, so if you run the program from a "set -e" script it will randomly fail. I guess that didn't bother whoever "allowed" that, but I consider it a bug.


It shouldn't in C++. Omitting an explicit return (or falling through to the end without hitting another return) should have the same result as if you ended it with `return 0`. If it's returning a random value then that is erroneous behavior. I've also never witnessed this and print non-zero exit codes in my command line prompt (so after execution my prompt looks like `blahblah(EXIT_CODE) $`).

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.


In C yes, on C++ it is required to return 0 if omited.


C99 also defines it:

>5.1.2.2.3 Program termination [...] reaching the } that terminates the main function returns a value of 0.


Thanks for the heads up, than it sums it up either the OP was using a broken implementation, or the incorrect language version.


There's an implicit return zero in C++.


Huh? We are using std as a module, but still not std::println?!


Not everyone has issues with iostreams.


I don't have the professional experience that most of the commenters here have, but I hear a lot of negativity. Like, a lot.

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 :)


Quite good reading to stay up to date how to write proper C++ code instead of classical C with C++ compiler, given how the language is anyway unavoidable in many domains until they migrate to something else, mostly beyond our lifetimes.

Like LLVM and GCC contributions, GPGPU frameworks and Khronos standards, language runtimes,...


> Quite good reading to stay up to date how to write proper C++ code instead of classical C with C++ compiler,

This is good too: https://github.com/isocpp/CppCoreGuidelines

I also liked Scott Meyer's book "Effective Modern C++".


Yes, although Scott Meyer's is now retired and his book series have stopped in C++14.

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.


Define “proper”. For me, “proper” is readable code without too much magic and over-reliance to compiler to do optimizations.

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?


Looking around the site, there's a free pdf chapter available via the publisher link (Chapter 12, Containers).

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.


There's a notion that one can prototype in Python and then just translate that easily to modern C++

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.


Performance, and not having two languages to worry about.

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.


Having left the C/C++ professional programming world several years back to wallow in other pastures, I've lost close touch with the languages except at a low-key hobbyist level. That said, I am curious over what is the motivation to pursue updates in 20 and 23? Are there really new features promised that today's programmer simply can't live without or are they all various levels of syntactic sugar or something in between? Is there a concern over whether these changes are making the language ever more complex and obese thus making mastery even harder to achieve?


> what is the motivation to pursue updates in 20 and 23?

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 safely implement scope guards

Can you elaborate on this?


A count of the number of exceptions in-flight was added, replacing the boolean indication of whether an exception is in-flight. This allows the scope guard construct proposed by Andrei Alexandrescu to distinguish between a scope being left on success and on an exception being thrown.

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


I can’t speak for all of C++20/23 but I was impressed by Concepts which finally make template compile errors legible


One of the things I've mostly been looking at is the additions to the standard library. Especially the new <stacktrace> header looks like something that should have been in the language already.


I like the new <bit> header. In C++/20 they added support for BSR and BSF instructions from 1985, introduced in Intel i386. In C++/23 they even added BSWAP instruction, much newer one, introduced in 1989, in Intel i486. Most other instruction sets (ARM, Power, etc) have equivalents of these instructions.

Currently I use C++/17, have to rely on compiler-specific intrinsics. They work fine in practice, but standard library functions are IMO better.


> Having left the C/C++ professional programming world several years back to wallow in other pastures.

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?


Having gone through a very similar journey, it took around 2 years for me to completely disassociate myself from a specific programming language. It was more a 'me' problem since I leaned on to a programming language rather than a problem domain.

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.


I have a bachelor and master of EE. My first job out of college starting my programming career (in Fortran), eventually moving to C and then C++. As my career progressed, I made myself into a software systems engineer. After several years of that, I started taking on full blown systems engineering things which I greatly enjoyed. That started my distancing from software development, mainly from interests but also because I became to expensive to write code. Fortunately, the companies I worked for were willing to support my career goals. YMMV.


This is an obvious ad to sell a book, but I wish more publishers would let you read one of the chapters without buying it first. Stroustrup has a lot of books and I have read some of them so he is a known entity, but I see ads like this all the time from authors I know nothing about. The preface and table of contents are good information, but they don't give you a good sense of the author's writing style.


If you click through to the InformIT site then you can get a PDF of Chapter 12 (Containers).


Is anyone reading the C++ standard or is it just me? It acts as an excellent reference manual.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: