Readit News logoReadit News
xdavidliu · 2 years ago
I find it really problematic that the "classic first program" in this book includes "import std;" as the very first line, and as far as I know not a single compiler with the possible exception of MSVC supports that out of the box.

Writing this on a debian machine, and trying "g++ --std=c++23 -fmodules-ts" does not work, and from https://en.cppreference.com/w/cpp/23 looks like the "paper" for this is P2465R3, for which clang++ 17 has "partial support". I apt installed clang++17, and it still didn't work, complaining "module 'std' not found"

I understand that "import std;" is a very new feature and not "finalized" or whatever, but this book is supposed to be for beginners to C++; I wonder how the average beginner would react to that?

(I found the same thing a year or two ago when reading "Tour of C++")

davidthewatson · 2 years ago
Good point! Me too.

My g++ emits exactly the errors and instructions you described.

I haven't read the current Stroustrup version under discussion, but I did read the earlier version when C++ was all day, every day for me.

I prefer Koenig and Moo's Accelerated C++ twenty years on though I admit there may be better books since which I've not read.

IIRC, their hello world was:

    // a small C++ program
    #include <iostream>
    int main()
    {
        std::cout << "Hello, world!" << std::endl;
    }
Which copy pastas into my current arch linux, builds in:

    g++ a.cpp 
and runs in:

    ./a.out
    Hello World!
as it has since I first read it twenty years ago, and likely did before that.

The rest of the book was a tour de force of making modern C++ emulate the near-pseudocode, sans pointer arithmetic of C, simple-and-clean, buttoned-up style seen in early python, where none of those things existed until pandas brought wrapped C++ libs along with it like numpy and scipy.

Professionally, I've not seen clean C++ code in the wild, though I don't work at FAANG and code reviews are unusual in rapid prototypes so I'm not sure how widely Koenig and Moo are mentored outside the greenfield world I've lived in with the possible exception of radiotherapy where you're trying to avoid being the next Therac 25.

adrian_b · 2 years ago
The current gcc documentation (13.2.1) says:

  "_Standard Library Header Units_
     The Standard Library is not provided as importable header units.
     If you want to import such units, you must explicitly build them
     first.  If you do not do this with care, you may have multiple
     declarations, which the module machinery must merge--compiler
     resource usage can be affected by how you partition header files
     into header units."
So for now any "import" can work only if one writes appropriate module files first.

Nevertheless, I do not expect that the updating of the standard C++ library of gcc will take a long time, so later this new book will become directly usable as it is.

For someone who already knows older C++ and just wants to update their knowledge, writing the corresponding module files can be a good learning experience in itself.

humanrebar · 2 years ago
At this point, it's not realistic to maintain interesting C++ programs without a build system. That being said, I expect the specific g++ example you provide will end up working with some special casing in the compiler, at least eventually, when someone submits patches to GCC to get it to work.

But mostly, it's not realistic to directly wire up calls to g++ anymore outside of research examples. Note that other compiled languages use systems like gobuild, cargo, Maven, etc. instead of fiddling with gccgo, rustc, javac, etc. directly.

https://www.kitware.com/import-std-in-cmake-3-30/

billforsternz · 2 years ago
I think your point is orthogonal to OP's point. I agree with him, the first chapter of a book about a programming language should include hello world and it should ruthlessly minimise barriers to the broadest range of possible readers being able to try that out. They can then supplement their reading with active experimentation, a vital step. You can't learn to swim by reading a book about swimming.
randomname93857 · 2 years ago
would this help with your problem with modules, it's referenced on the book's page: https://www.stroustrup.com/module_use.html ?
xdavidliu · 2 years ago
> GCC

> CGG (sic) uses .cxx for module files Use -fmodules to use modules.

no it does not. Trying this on Fedora 39 for example, my original comment above already had -fmodules-ts, and when I use -fmodules, g++ errors with

g++: error: unrecognized command-line option ‘-fmodule’; did you mean ‘-Mmodules’?

tejohnso · 2 years ago
Oh, he switched to QT for the GUI chapter. That's a significant change from FLTK. Should be well received as QT is popular in industry. Not sure how the learning curve will be affected.
iso8859-1 · 2 years ago
I wonder what Stroustrup thinks about the Meta Object Compiler. In a way Qt is its own dialect of C++.
SubjectToChange · 2 years ago
The MOC is just a code generation tool, it's about as objectionable as bison. A far greater sin, especially in the eyes of Stroustrup, is disabling exceptions
justin66 · 2 years ago
He's name-dropped CopperSpice in some of his speeches, so he's certainly aware that it's not universally adored.
pjmlp · 2 years ago
For the better, with Qt there is QtCreator.
spacechild1 · 2 years ago
Not sure what you are trying to say here. Qt, the library, and QtCreator, the IDE, are completely separate products. You can use QtCreator without Qt and vice versa.

Now, I'm pretty sure you know that, hence my confusion...

layer8 · 2 years ago
He uses a custom wrapper library, so not sure how much (if anything) of QT proper is exposed.
UncleOxidant · 2 years ago
All of the 4 AI coding assistants I've tried (claude3, gemini, gpt4, deepseek) used SFML for graphics when I asked them to code boids and game of life in C++. I'm wondering if that's because it's cross platform or that there's more code out there using SFML that these models got trained on? SFML seems relatively recent compared to Qt or even FLTK, so it seems kind of odd that there would be more SFML training data. It also seems odd that all 4 were in agreement here that SFML should be used for graphics in a C++ program.
forgotpwd16 · 2 years ago
SFML is a graphical library but not a GUI framework/toolkit that Qt/FLTK are.
swatcoder · 2 years ago
SFML is more accessible for lightweight/exploratory/educational use, and so I wouldn't be surprised if it appears more often in training data associated with those simple "let's learn" sized projects.
chuckadams · 2 years ago
Know what I like about Stroustrup's code? "using namespace std;". The typical convention of sticking std:: in front of std::every std::last std::bloody std::thing drives me std::insane.
HarHarVeryFunny · 2 years ago
It depends ...

You should NEVER have "using namespace" (for any namespace) in a header file, since that is how you create name clashes, which is what the namespaces are there to avoid.

I don't personally like "using namespace std;" even in implementations, since I think it makes code less readable, and the contents of std:: is so large, and growing, that I'd again prefer to just avoid the possibility of name clashes.

We write code once, but read it many times, so shorter names (incl. namespaces) seems like a poor efficiency choice.

Kranar · 2 years ago
>We write code once, but read it many times, so shorter names (incl. namespaces) seems like a poor efficiency choice.

I think it's fascinating how different people can interpret this so differently. I feel like it's precisely because we read code so much more than we write it that we should prefer using names that get to the point, instead of having so much noise and repetitive boilerplate.

Reading a soup of std::this, std::that, std::foo, std::bar is so difficult to parse through. Especially if you're like me and you sound things out in your head, which I recently learned is not how everyone reads.

The only justification for writing all those std::'s is because compilers can't disambiguate names from their context, but you're not going to find a human who comes across a use of vector<Foo>, or sort(...) and throw their hands up in confusion wondering what was meant.

>We write code once, but read it many times, so shorter names (incl. namespaces) seems like a poor efficiency choice.

This to me seems like a cargo cult justification, where you've heard the argument that descriptive names are helpful for readability, so we should name our variables in a way that conveys their intention as opposed to 1 letter names or obfuscated abbreviations, but instead of genuinely understanding the principle behind the rule, you think the rule is simply that it's better to have long names over short names.

Descriptive names that can be used to disambiguate variables from one another on the basis of their purpose... yes, please do that. Writing long names just so that they are long, especially by giving everything a shared prefix like std::... no, that's a misunderstanding of the justification behind the rule.

It's similar to that saying along the lines of when a principle becomes a metric, it ceases to be a useful principle.

ryandrake · 2 years ago
Not only that, but you have no idea what's going to be put into the standard tomorrow.

If code I write today has a class called bubble_sorter, and then one day, the C++ standard library decides to add std::bubble_sorter, then:

1. If I had "using namespace std;" then all of my code is suddenly broken.

2. If I didn't have it, I'm fine.

Also, and this is just personal preference, but I simply like to be able to clearly distinguish when my code is calling into the standard library. Typing in that short "std::" reminds me that I am calling into someone else's code.

culi · 2 years ago
Conversely,

We write code once, but read it many times, so longer names seems like a poor efficiency choice.

winwang · 2 years ago
Yep, although I do like not having clashing names.

But I mean... somehow every other language solved this.

Jtsummers · 2 years ago
> But I mean... somehow every other language solved this.

Did they? C, Lisp, Rust, Python, Ada, Go, Java, C#, ...

They all require you to qualify conflicting names if some other characteristics (for instance the number or types of arguments) don't provide enough information, or outright don't permit it (C, since it has no notion of name spaces).

Can you point to the "every other language[s]" which have solved this problem?

zengid · 2 years ago
I hear that once c++ modules lands this shouldn't be controversial anymore, right?
Koshkin · 2 years ago
It’s not so much the ‘std’ thing, it’s the double colon that is an abomination. I never understood why they couldn’t simply use a single dot like some other languages have done.
Maxatar · 2 years ago
To resolve ambiguities due to the fact that in C, type names live in a separate namespace from variable names so that it's possible to have a variable with the same name as a type.

C++ inherits this distinction so that it is possible to write the following:

struct foo { int x; };

struct bar : foo { ::foo foo; };

bar b;

b.foo::x = 1;

b.foo.x = 2;

The b.foo::x and b.foo.x are two different x's, and the only way to disambiguate them is through the use of the . or the ::

pif · 2 years ago
You learned to program on Windows, didn't you?
chuckadams · 2 years ago
I learned on C on Unix. The naming conventions in Windows are the same kind of syntactic noise I dislike: long identifiers that are just long without actually being descriptive, with extra crap ladled on top in the form of Hungarian notation (which had its uses in the Excel codebase, but doesn't belong anywhere near C++)

BeOS probably had the nicest looking API. Let's hear it for is_computer_on_fire()

marcosdumay · 2 years ago
lpsiNo, spbI uiOnly lpwAdopted iThe spdwStyle usLater.
ben7799 · 2 years ago
Haven't used C++ in 10+ years but I remember studying an earlier version of this book in stupid depth. And this was at the end of 4 years of using 99% C++ in college.

It's such a good book. If you really take the time to understand the book C++ it seems kind of sad the world was so afraid of it.

But of course after all this I of course met an army of people who had never read a book like this at all and wrote horrifying C++ code.

jdlyga · 2 years ago
I miss my days working with C++. It's moved further down the development stack than where it used to be. We used to handle UI, API parsing, and pretty much everything using C++.
JonChesterfield · 2 years ago
I felt some nostalgia for Fortran a while ago. Spent half an hour programming in it, cured. Maybe take a shot at parsing JSON in C++ and see if the nostalgia survives the process.
jbandela1 · 2 years ago
>Maybe take a shot at parsing JSON in C++ and see if the nostalgia survives the process.

I have used this library in the past and was actually pretty easy

https://github.com/nlohmann/json

ChuckMcM · 2 years ago
It took 30 minutes to cure you?!?

One of the first things I did when I got my PiDP-11 which can run RSX-11M and the DEC fortran compiler. I spent many many hours programming in Fortran when I was in college and thought wow I could relive some of that, about 5 minutes in I was "okay, step slowly away from the console." :-)

VHRanger · 2 years ago
Let me carefully copy paste my personal stringutils.hpp file of string handling routines and I'll be right up to it!
petsfed · 2 years ago
I recently had to port an existing C++ JSON parser into a new project, and even though it was complete in terms of what we needed it to do right now, adding any kind of additional functionality to it would've been a nightmare.
pantsforbirds · 2 years ago
If you have any problem that isn't vector math, it's absolutely awful. Even IO is unpleasant
freedomben · 2 years ago
Same. I really miss it. Not terribly long ago we had an app that has a client and server, both in c++. UI, API, everything was c++. It really felt like the universal language had arrived. I won't pretend everything was perfect as it wasn't, but work was fun and the high caliber of people who could work in that stack was a joy to work with. I've never had a more exciting lunch than when we got distcc running on our blades so we could execute builds way faster. It was also a joy not being the only Linux zealot :-D
zerr · 2 years ago
I guess the scarcity of cheap labour contributed to the demise of C++ in the applications world.
VyseofArcadia · 2 years ago
At my work pretty much everything but the UI is in C++. I suspect the only reason the UI isn't C++ is so we have a portion of the cosebase that recent grads can work on right away without having to train them up in C++.
dkersten · 2 years ago
I still tinker on a game engine personal project just to scratch the C++ itch. I really like using C++, despite all the hate it gets.
KptMarchewa · 2 years ago
I just wish to _not_ work with Python.
REDS1736 · 2 years ago
Why is that? I'm genuinely curious. Also, what languages / environments do you prefer?
zerr · 2 years ago
Often I think that I'm lucky, still working on C++ desktop applications.
Night_Thastus · 2 years ago
Where I am, we still do!
freedomben · 2 years ago
What libraries are you using? Qt? Do you use anything for database access and rest API (or protobufs like we did) or just custom code?
deeznuttynutz · 2 years ago
Over the past year, I've completed most of the second edition. It truly is an amazing book that has helped me overcome many mental barriers I've faced with programming for years. The main reason for the reduced size of this edition is the removal of 'Part IV: Broadening the View.' This section, which covers additional topics such as text manipulation, numerical computing, and embedded systems, is now available online. The chapters have not been updated from the second edition, as the topics are still relevant and utilize C++11/14.
dzogchen · 2 years ago
Sharing the C++ Annotations here, which is a continiously updated book on modern C++. http://www.icce.rug.nl/documents/cplusplus/
hnthrowaway0328 · 2 years ago
If I just use C with classes, plus smart pointers and auto, for my emulator project(s), would that be a reasonably good approach?

I once heard that the C++ language contains 4 components: the first catalog is "C", the second is for OOP, the third is for productivity and flexibility such as stl and templates, and the last one is for special cases such as volatile, asm, etc. He then recommends to use catalog 1 with care, and avoid scenarios that one has to use catalog 4. Does that make sense?

Night_Thastus · 2 years ago
I started off writing C++ this way, basically writing it like it was C89.

This is fine if you do not plan to share your work with others, but it's not well-written C++. It will bite you later on. It's best to learn the C++ way of doing things. It will save you so much time and headache. Don't use character arrays, use strings. Don't use C arrays, use std::vector or std::array. Don't write your own lists or sets, use std::list/set or std::unordered_list/set. Don't use strcat when std::string operator + exists. Etc.

I personally rarely use smart pointers or make_shared/make_unique these days. I just don't need pointers. Most of the time allocation can be done without them, and when I need to pass things around I use references. There are exceptions for C APIs for cross-platform/cross-compiler work, of course. And sometimes library code needs it, ofc.

The STL and <algorithm> are your friend. They solve so many problems in a very elegant way. Learning them should be a priority.

I'd go easy on the OOP elements unless you know OOP programming very well. Just using classes as containers for data and functions is more than fine for C++ most of the time.

Writing your own templates can be a bit of a footgun until you understand them. Feel free to put that off awhile.

Don't mess with volatile and asm unless you are 100% sure that what you're doing needs it.

Also: Be cautious with use of auto. A bit here and there is fine, but too much and code can become unreadable. C++ is a typed language for a reason.

HarHarVeryFunny · 2 years ago
Yes, roughly so.

1) The major part of C to avoid is raw pointers and malloc, and generally anything where C++ has a more modern alternative. Don't use C datastructures (pointers, strings, arrays) where C++ replacements exist (smart pointers, std:string, std::array and std::vector, etc), or use C libraries where C++ replacements exist (e.g. C++ std::string vs C's string.h).

Of course you can't avoid all of C, since the syntax of C++ is an extension of C.

2) I wouldn't characterize what C++ adds to C as OOP. OOP is a design methodology, whereas the main addition C++ gives you is classes which are better thought of just as powerful and convenient type of data structure.

The core feature of classes you always want to use are constructors and destructors. Any initialization of the class's data members should be done in the constructor (don't leave things uninitialized), and any final cleanup (releasing memory or locks, closing files, etc) should be put in the destructor so that it always happens (even if your program throws exceptions).

Don't feel that just because classes support subclassing, polymorphism (virtual methods), etc, that you should be using them. They are there in case you need them, but if in doubt don't.

3a) The STL is just the standard library for C++. You should always be using STL data structures (std::string, std::list, std::vector, std::map, etc) when applicable - not just "for productivity".

3b) Templates (template classes, constructors/methods, functions) are not needed for most everyday use of C++. They are there for library writers, and on occasion for writing your own class and libraries. Think of them a bit like class inheritence - they are there in case you need them, but not something you should be reaching for unless there is no better way.

4) C++ has a LOT of stuff (esp. libraries) that might be considered as "for special case use only". A rookie mistake might be to think that C++ has all this stuff - I should be using it! In general you should ignore the obscure stuff, and only use it when some special circumstance requires it.

hedora · 2 years ago
These days, OO programing is mostly frowned upon. OO added the idea of implementation inheritance to interfaces, and that's mostly a bad idea.

Newer languages and modern C++ favor composition instead. You define interfaces that provide some well-defined capability, and then you write things that wrap the interfaces to provide additional functionality. In C++ you can use templates to do this without any runtime overhead. In C, you can either use preprocessor macros (ouch) or you can build your own vtables. The vtable approach adds virtual method invocations all over the place, so it's not zero cost.

The C++ approach actually isn't zero-cost either: You can end up having many copies of the same template logic, which blows up your instruction cache. One of the big innovations of swift was to avoid that. As far as I know, Rust macros and "go generate" produce binaries that are closer to the C++ approach.

Anyway, especially for emulators, you should look into getting good with C++ template meta programming, or just learn rust and then use its implementation of generics. Both approaches will let the compiler inline the heck out of stuff that ends up in the inner loop. In particular, clang + gcc are both good at constant propagation.

One problem with jumping straight from C to rust is that you basically have to already be able to write stable C++ code in order to get it to compile at all. The borrow checker moves subtle but common C++ errors from runtime to compile time. If you have a lot of experience with C already, the jump might be OK.

(edit: I should add that C++ isn't standing still, and there are lots of cool efforts to backport the good ideas from Rust to it. Systems language competition is a good thing, and they're my two favorite languages!)

Deleted Comment

Thorrez · 2 years ago
I get a 404
Jtsummers · 2 years ago
rubymancer · 2 years ago
I expected it to be even more of a tome, but surprisingly it's been cut in half!

2nd edition:

Paperback ‏ : ‎ 1312 pages

Item Weight ‏ : ‎ 4.81 pounds

3rd edition:

Paperback ‏ : ‎ 656 pages

Item Weight ‏ : ‎ 2.71 pounds

giaour · 2 years ago
From the preface, it looks like a bunch of the reference material has been cut from the book in favor of C++ documentation on the internet:

"The third edition of Programming: Principles and Practice Using C++ is about half the size of the second edition. Students having to carry the book will appreciate the lighter weight. The reason for the reduced size is simply that more information about C++ and its standard library is available on the Web."

mirekrusin · 2 years ago
Nice to see C++ knowledge counted in pounds! :)
JAlexoid · 2 years ago
And it's 1229g for the rest of us.
kevindamm · 2 years ago
To be fair, someone should print the online reference material to get the real comparison.. it's not like we have fewer details in the standard library -- footnotes about compatibility with which version(s) and the related semantics could fill a book on its own.
kstrauser · 2 years ago
Literally exactly in half. Did they pick a smaller font or something?