245 points · by jrepinc · 2y ago · 226 comments
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++")
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.
"_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.
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.
> 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’?
I think you've missed the whole point. No one cares about implementation details. The critical aspect is that Qt imposes the use of a superset of C++ which includes keywords such as signals and slots. Technically it's not even C++, but a language which has its own unique keywords, concurrency model, object ownership and life cycle, etc.
Now, I'm pretty sure you know that, hence my confusion...
The idea that "QtCreator" is some totally independent IDE that just coincidentally happens to have the letters Qt at the beginning in the same way that Java and JavaScript are independent of one another, but otherwise has no relationship to Qt the library is just patently absurd HN pedantry.
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.
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.
Well, no, I've been a professional programmer since 1982, and a hobbyist one both before then and to this day.
I might be wrong, but these are the lessons I've learnt over the decades working on a variety of projects of different size and durations ...
Of course consise code is nice, and while you're in the heat of development it's easy to pretty much memorize an entire codebase, even a large one, but it's when you have to come back to it years later, and barely even recognize the code as your own, that you'll be happy it's self-documenting. Now, on a large team that "future self" may just be the new hire, or the guy who replaces you when you quit ...
Sneaking using namespace directives in interface headers is a well known source of problems, as it inadvertently introduces names to lookup which can and often clash. I mean, think for a second: why are namespaces used? What problem do they solve? And why do people think it's a good idea to add all names to a custom namespace?
Well, adding those names to interface headers negates all that.
That's why some people interpret things differently: they are oblivious to this problem as their negligible experience means they never experienced any of the problems they cause.
Bjarne's book seemed to be a comprehensive introduction and I'm currently going through it. I found that adding "using namespace std" at the beginning of the file reduced some of C++'s syntactic overhead that a beginner such as myself has to account for. It allows me to focus on the essential by learning the programming principles, rather than getting stuck on the syntax and having to (annoyingly) repeat std:: every line.
Nevertheless, I think every beginner should know the disadvantages of setting the namespace at the beginning of the file and that no one should use it in production code, but it does its job at keeping things simple if I'm just starting out with C++. There is a reason why Bjarne does this in his book, and I can see why.
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.
If this happened and if you included that specific header, you would get a simple compiler error due to ambiguous methods. Then you can simply add a namespace somewhere and move on. I know sometimes this can involve a lot of changes (if we're talking about other `using namespace ...` usage) but in general you're not gonna have problems.
If you're really worried about this, you can move the statement closer to where you need it. This is very helpful for dense code that you normally want to be verbose.
We write code once, but read it many times, so longer names seems like a poor efficiency choice.
Certainly time to enter code (which is increasingly going to be automated) should be the last consideration - if we're considering full software lifecycle then coding probably takes up some small single-digit percentage of the time we're interacting with the code.
How can you tell what's the type of an ambiguous name if you have no indication of which namespaces are within scope?
I mean, think about it. If your concern is readability, doesn't this mean it's important to know what code you're looking at?
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?
import {vector} from 'std';
Which I think is a reasonable compromise, you're only bringing vector into scope rather than all of the standard library.
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 ::
BeOS probably had the nicest looking API. Let's hear it for is_computer_on_fire()
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.
I have used this library in the past and was actually pretty easy
If I have an existing JSON file that I want to quickly parse for a demo project there is almost zero chance I would pick C++. In comparison, Python is already installed in many environments and has built-in json parsing.
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." :-)
I really wish there were more string util functions in Cpp. I mean C had strtok()!
Sure the builds are slow and Python _kinda_ has static typing, but rust just has a lot of stuff I like and it's practical to install and use natively without learning all the jargon like venvs and eggs and wheels and which package manager and package manager manager (rye?) to use this year
I tried Python years ago and never got the motivation to push through that learning curve. I've used c++ a lot but it always required me to "keep my hands inside the ride at all times". Rust feels like it actually wants to be easy to use
The actual language is not awful. Some features are even nice, like infinite precision integers by default, and separate / and // operators.
Language is ok. Setting everything up is atrocious.
The other quite annoying thing is that the docs are extremely badly organised so Google rarely points you directly at what you want. Instead you get stuff like w3schools which is trash, but much better organised. Also annoying that the docs still don't include types.
I would use Typescript (via Deno), Go or Rust instead. There are some other Python replacement languages I haven't tried yet that might be an option like Mojo, Lobster, Nim. Probably still too niche for production; I'd stick with Typescript.
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?
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.
If that paragraph doesn't make any sense, and you think you need volatile then there are basically two possibilities: You're writing a Java program (which uses that keyword for something else), or you need std::atomic (or __sync_* for C) instead.
Yes, although one place where "auto" should almost always be used is to declare iterators (not that one should be needing them so much nowadays), and I think harmless for range-based for loops "for (auto i : v)" although as you say there's definitely a convenience/readability trade off.
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.
The Standard Template Library is Alexander Stepanov's generic programming achieved via the relatively new (at the time) C++ Templates feature. At this point (the late 1980s through early 1990s) Generic Programming is an obscure academic idea, it's not how normal software works. Stepanov is persuaded to present his library to WG21 ("the committee") in 1993 and their work is eventually standardised as C++ 98 a few years later.
The most important part of the STL is the algorithms, generic algorithms are an amazing idea. The collections, eh, they're nothing to write home about, there are a dozen takes on the iterator problem with different trade-offs, but this idea of generic algorithms unlocks so much power and that's why lots of languages grew generics or for new languages had them on day one.
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!)
Only in certain circles. For the software world as a whole, "mostly" is rather an overstatement. (For that matter, for the software world as a whole, "mostly" is an overstatement no matter what claim follows the "mostly".)
> OO added the idea of implementation inheritance to interfaces, and that's mostly a bad idea.
There is more than one flavor of OO. Not all of them support implementation inheritance. You're using a feature of a sub-part to complain about the whole. (In fairness, though, this is a thread about C++...)
Current best practice is "prefer composition over inheritance". There are places, though, where inheritance is the correct answer. When you hit those places, use it. Where it's not, don't use it.
linkers have been able to perform identical-code-folding optimizations for a few decades now
Without having to squint, 12 of those languages are easily categorized as OO languages. Given the mindshare of those 12 languages, I don't think it makes sense to say that "OO programming is mostly frowned upon." [emphasis added] Maybe it's frowned upon by some, maybe even many, but if it's mostly frowned upon then a lot of people must hate their work.
Thank you in advance!
2nd edition:
Paperback : 1312 pages
Item Weight : 4.81 pounds
3rd edition:
Paperback : 656 pages
Item Weight : 2.71 pounds
"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."
#include<stdint.h>
#include<list>
#include <map>
#include<unordered_map>
#include <set>
#include<memory>
#include <algorithm>
https://www.stroustrup.com/PPPheaders.hEven if you're an experienced programmer or have no interest in C++ you should still read this book.
It's one of the best examples of technical writing and teaching computer programming that I'm aware of.
I recently started at a company with a bit of a hairy c++ application that I would love to refactor or understand more thoroughly. Is this book a good place.
Note that I have read a very basic book on C++ much more learning programming book, but got me introduced to the memory management concepts.
As well I've been getting through Effective C++: 55 ways..., but this seems more like a tips and tricks and I don't think I'm getting much out of it.
If you want to work on your "hairy c++ application" you'll benefit from understanding how "modern c++" it is (and what your toolchain supports).
Meyer's effective books are good with two caveats: first, they are really meant to improve practice for people who are already working in the language (e.g. don't do it that way, and here's why). Second, the older ones are now dated and some advice need updating to work with newer language spec.
If 3rd edition of this one lives up to previous, it should be a pretty good read but as others have mentioned the "Tour of C++" book is a good entry.
If you just started learning C++, why did you choose it instead of another language? (Rust, C#, Go, etc)
I know a bit of C but feel that the sheer "thickness" of C++ is too daunting and scary to even start.
On the other hand, if you don't need these "hard-core" features then any language will do. In fact, most of these have Python or other language interfaces so you don't need to know much C++.
I would suggest a better phrasing might be that you should learn C++ if you want to cling to existing software in the state it is today, certain that history ended yesterday and the future is just the same forever from here on.
You won't get "extreme performance" from C++ because it is buried under the weight of decades of compatibility hacks.
You won't get "extreme performance" from C++ because it is buried under the weight of decades of compatibility hacks.
This doesn't even make sense. What is an example of something that can't be fast because it is done in C++? What "compatibility hacks" are slowing programs down?
This does not sound like something someone with experience in C++ would say.
No one learns all of C++, you just need to learn the bits that are useful for the kinds of applications you write. If, for example, you are building database kernels then you are unlikely to use any of the STL containers (even std::array and std::vector are infrequent) in most of the code. However, you will need to know how to manually fix-up object lifetimes using semi-obscure language features you would never need to know about for most server apps.
If you stay within a relatively narrow application domain, the useful parts of C++ for that domain crystallize pretty readily in my experience, which is much easier to learn.
The compiler attempts to track object lifetimes for the purpose of optimization e.g. if the object contains a notionally immutable value it doesn’t have to re-read the value during the object’s lifetime. A lot of compile-time code optimization is based on knowing when an object at a memory address is changed or destroyed. If the objects don’t get destroyed but merely disappear, or worse, are replaced with a different object at the same address, and the compiler can’t see that at compile-time then the compiler assumes it doesn’t happen. This violates strict aliasing rules in C/C++ even though there are legitimate reasons for this to occur. C/C++ systems code, like Linux, commonly disable strict aliasing rules because it causes undefined behavior, even though it also disables certain optimizations.
In the last several revisions of C++, they have added blessed methods of informing the compiler when these object lifetime rug-pull situations occur, so that it can optimize around them without disabling the optimizations enabled by strict aliasing. This includes functions like std::launder, which acts like a constant folding barrier i.e. the compiler can’t assume that constants at that address prior to the barrier call are still operative when generating code. There are a couple other functions in C++23 that explicit take a memory address and explicitly start a new lifetime with an arbitrary type, without constructing a type at that address; these are no-ops, all of these functions are compiler annotations, they don’t generate code. These are blessed ways of doing more hack-ish ways of effecting the same result in recent versions of C++ (e.g. the memmove/launder trick). In old versions of C and C++, the ways of doing this were technically undefined behavior but the compiler writers unofficially provided ways to work around this that would behave as needed since it had valid use cases, which is not a great way to work.
This doesn’t just affect lifetimes, though that is most of what the fix-up is about. Mutability of references is similarly fuzzy and it is impossible for a good design to guarantee that multiple mutable references don’t exist, so you need other mechanisms to guarantee they never conflict. However, these fix-ups are above the level of the compiler.
In the extreme case of database kernels, most objects have an ambiguous lifetime and uncertain address. Consequently, you have to create object reference wrappers that hide what is required to ensure strictly defined behavior in these cases and to ensure conflicts can’t happen. Wrapping your object references with some small hygienic functions can eliminate the issue.
You may start with simple audio plugins. Have a look at JUCE (https://juce.com/)!
Realtime audio programming has some rather strict requirements that you don't have in most other software. Check out this classic article: http://www.rossbencina.com/code/real-time-audio-programming-...
Is there something like this for Rust?
Any recommendations?
[1]:https://www.amazon.com/Programming-Principles-Practice-Using...
Edit: emailed Mr. Stroustrup and he just replied to say that the bad ISBN has been corrected.
I think you just earned yourself a coveted check for `sizeof(attaboy)`, and I’m jealous.