[HN Gopher] 3rd Edition of Programming: Principles and Practice ...
___________________________________________________________________
3rd Edition of Programming: Principles and Practice Using C++ by
Stroustrup
Author : jrepinc
Score : 217 points
Date : 2024-04-19 13:45 UTC (9 hours ago)
(HTM) web link (www.stroustrup.com)
(TXT) w3m dump (www.stroustrup.com)
| dzogchen wrote:
| Sharing the C++ Annotations here, which is a continiously updated
| book on modern C++. http://www.icce.rug.nl/documents/cplusplus/
| Thorrez wrote:
| I get a 404
| Jtsummers wrote:
| From https://www.icce.rug.nl/ I got https://fbb-
| git.gitlab.io/cppannotations/, which does work.
| repelsteeltje wrote:
| Link works for me (firefox 125), but only if I use http
| (port 80), port 443 get me 404 not found as well.
| Jtsummers wrote:
| Ah, you're right. The issue is the link switching from
| http to https (even though the supplied link is http) and
| Chrome making it difficult (by default) to see whether
| http or https is being used. If I just copy/paste the
| link it works fine in Chrome and Edge but clicking on the
| link they both switch it to https. Brilliant.
|
| Just tested, works fine with Safari (mobile, but desktop
| usually has the same behavior).
| repelsteeltje wrote:
| The webserver setup seems sloppy. If the site is http
| only, have https redirect to port 80 or remove the vhost
| altogether. Not great for an educational institution
| doing serious computer science.
|
| Chrome's attempt to use a secure connection resulting in
| 404 while the actual link works fine isn't great. But
| it's understandable and the TLS-first assumption the're
| using probably works just fine in the other 99.999%
| situations.
|
| If only they'd taken the time to copy the http config and
| setup let's encrypt or cert from GEANT Vereniging CA
| apparently preferred by rug.nl...
| hnthrowaway0328 wrote:
| 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 wrote:
| 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.
| hedora wrote:
| In particular, you don't need volatile unless you're
| writing hardware device drivers. If you're doing that, then
| you also need to understand the semantics of the memory
| mappings of the I/O pages you're writing. You also need to
| know about bus ordering and request coalescing guarantees
| for PCIe (or AXI, or whatever your embedded system uses).
|
| 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.
| gpderetta wrote:
| > (or __sync_* for C)
|
| Actually even C has _Atomic these days!
| HarHarVeryFunny wrote:
| > Be cautious with use of auto. A bit here and there is
| fine, but too much and code can become unreadable.
|
| 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.
| hedora wrote:
| 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!)
| jcelerier wrote:
| > You can end up having many copies of the same template
| logic, which blows up your instruction cache.
|
| linkers have been able to perform identical-code-folding
| optimizations for a few decades now
| Jtsummers wrote:
| https://www.tiobe.com/tiobe-index/
|
| 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.
| bmoxb wrote:
| They are, if I'm understanding correctly, referring to
| what may be considered the 'traditional' OOP style
| (Animal, which has various properties and behaviours, is
| extended by Dog, which has its own properties and
| behaviours, maybe overriding those of Animal) vs a style
| where inheritance is use primarily to define and
| implement interfaces (i.e., an expected set of behaviours
| with no implementation included in the base class). In
| other words, the different ways a language supporting OOP
| may be used rather than what the language supports in and
| of itself.
| AnimalMuppet wrote:
| > These days, OO programing is mostly frowned upon.
|
| 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.
| m_nyongesa wrote:
| Do you have a recommended link to a book or tutorial that
| teaches one how to do composition rather than inheritance
| in C++ (the way you are describing)?
|
| Thank you in advance!
| HarHarVeryFunny wrote:
| 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.
| tialaramex wrote:
| Although Microsoft refers to their implementation of the
| standard library as the STL (and this is convenient naming,
| since one of its most important maintainers is STL, Stephan
| T. Lavavej) actually the STL and the C++ standard library
| aren't the same thing.
|
| 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.
| HarHarVeryFunny wrote:
| Sure, but that's really more of a historical perspective.
| The STL is still there as part of the standard library,
| although basically just the containers portion. It's been
| so long since I used the original standalone (SGI)
| version of the STL, that I can't even recall exactly what
| was in it other than containers and iterators (any
| algorithms?).
| mindcrime wrote:
| Huh. The ISBN shown at the top of the page (currently
| "9780136816485") appears to be incorrect. That seems to be the
| ISBN for "A Tour of C++" from 2022. The ISBN for _this_ book is,
| according to the Amazon product page[1], "9780138308681".
|
| [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.
| sebstefan wrote:
| Already teaching you about the maintainability of tightly
| coupling different parts of your system before you've even
| opened the book
| arrowleaf wrote:
| It would have been awesome if that ISBN issue were an actual
| ISBN re-use issue. I've run into issues coupling my system's
| design to the assumption that ISBNs uniquely identify a
| single edition of a single book. The intent of ISBNs are to
| be unique, but mistakes are made and resellers lose track or
| straight up abuse some ISBNs.
| lstamour wrote:
| Not just that but when ISBNs were first introduced, it was
| common thought that they were used for cash register price
| scanning rather than computer-controlled inventory, so a
| number of early books had ISBNs re-used by publishers and
| it wasn't caught because they were meant to be the same
| price. These days you often see two barcodes on books, one
| is the ISBN and the other is the price.
| layer8 wrote:
| Even Stroustrup falls prey to copy&paste programming.
| b33j0r wrote:
| Darn, I don't think Bjarne sends $2.56 checks.
|
| I think you just earned yourself a coveted check for
| `sizeof(attaboy)`, and I'm jealous.
| mindcrime wrote:
| Just being able to say that I got a response from Bjarne
| Stroustrup is reward enough in its own right!
| dlachausse wrote:
| Actually he does respond to emails and he is responsive to
| constructive feedback from my experience.
| beryilma wrote:
| I still remember "reading" his entire 1000-page C++ book for
| the sole purpose of finding an error on it, for which I was
| handsomely rewarded with a $32 check from Bjarne. Still not
| cashed. Good times...
| rubymancer wrote:
| 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 wrote:
| 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 wrote:
| Nice to see C++ knowledge counted in pounds! :)
| kevindamm wrote:
| 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.
| JAlexoid wrote:
| And it's 1229g for the rest of us.
| kstrauser wrote:
| Literally exactly in half. Did they pick a smaller font or
| something?
| FrustratedMonky wrote:
| I love this book. I wish other languages had something similarly
| held in high regard to provide some touchstone.
|
| Is there something like this for Rust?
| panqueca wrote:
| https://github.com/sger/RustBooks
| skilled wrote:
| Excellent! I have recently started doing the learncpp.com
| tutorial and I think this book might have come at the right time.
| pajko wrote:
| You might find the courses useful too:
|
| https://github.com/federico-busato/Modern-CPP-Programming
|
| https://learnmoderncpp.com/
| dboreham wrote:
| First edition was the right thickness imho.
| jdlyga wrote:
| 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++.
| Night_Thastus wrote:
| Where I am, we still do!
| freedomben wrote:
| 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?
| Night_Thastus wrote:
| Qt for everything UI-related, yes. SQLite for databases,
| though looking again that code is actually Python. Nothing
| networked, so REST isn't relevant.
| freedomben wrote:
| 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 wrote:
| I guess the scarcity of cheap labour contributed to the
| demise of C++ in the applications world.
| KptMarchewa wrote:
| I just wish to _not_ work with Python.
| REDS1736 wrote:
| Why is that? I'm genuinely curious. Also, what languages /
| environments do you prefer?
| 01HNNWZ0MV43FF wrote:
| Not gp but I prefer rust to python and I'm itching to try
| that "just write your build scripts and stuff in rust too"
|
| 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
| gorjusborg wrote:
| The idea of using Rust for scripting is bizaar.
|
| I can understand not wanting to use Python for
| everything, but I see the problem being the 'use it for
| everything' not the language choice.
|
| Use the tool that excels at the job. There is no language
| that is good at everything.
| natsucks wrote:
| Rust is cool now. Python is not cool anymore.
| steve1977 wrote:
| I think Python fell victim to the Peter Principle. It got
| promoted beyond its competence.
| germandiago wrote:
| Python does well for several reasons.
|
| Some that come to my mind: its versatility binding native
| code and its easy-to-fit in your brain mental model for
| many tasks. The fact that you can script with Python
| without a compilation step also helped a lot to spread
| its popularity I think.
| rightbyte wrote:
| The way you define the entry point function is so bizarre
| I assume scripting was the original use case.
| AnimalMuppet wrote:
| Having to use the wrong tool is not cool, ever. So I
| don't care how cool Rust is right now, I still am not
| going to use it for scripting.
| weinzierl wrote:
| Have you tried it? How would you know that Rust is the
| wrong tool.
|
| I'm indifferent when it comes to Python vs Rust for
| scripting, but I'd take Rust over a shell script (of any
| variety) any day.
| AnimalMuppet wrote:
| There are many things I have not tried, ranging from Rust
| to heroin. "You don't know because you haven't tried it"
| is _really_ bad epistemology.
|
| It's also totally impractical. Rust isn't the only
| language I haven't tried; there are more than a thousand
| of them. I'm not using JOVIAL for scripting, or Fortran,
| or a bunch of others. No, I haven't tried any of those
| either. No, I'm not going to.
|
| Turning specifically to Rust, I don't use it for
| scripting because it's not what I look for in a scripting
| language. It's compiled; I look for a language that
| doesn't have that extra step. It has the borrow checker;
| I don't write scripting code that needs that level of
| discipline and care.
|
| In fact, most of my scripting is of the form "pick some
| bits out of a text file". For that, Perl is my tool of
| choice. Sure, other languages have regexes. None of them
| do it as cleanly and simply as Perl. (Note well: "clean"
| does not apply to the Perl _syntax_...)
| smallstepforman wrote:
| The current project I'm working on has tons of resource
| caches (for performance), with tons of non-owning
| pointers sharing cache references. I'd hate to do this in
| opinionated languages like Rust.
| n_plus_1_acc wrote:
| cargo -Zscript is in nightly
| weinzierl wrote:
| > _The idea of using Rust for scripting is bizaar._
|
| Not at all, I do the same.
| steveklabnik wrote:
| Incidentally, this thing comes up a lot: Python vs Rust
| for scripts. I wrote a comparison four years ago:
|
| https://news.ycombinator.com/item?id=22712441
|
| And updated it six months later:
|
| https://news.ycombinator.com/item?id=24595081
|
| That's still how I'd do this task today.
|
| Anyway, I don't think that Rust is always a great choice
| for scripting, but if you already know Rust, it's totally
| fine at it.
| germandiago wrote:
| Same for C++ with a good options library and
| std::filesystem IMHO. You can kind of script with that. I
| did it and was surprised it did well for some of my
| engine tooling.
| e44858 wrote:
| For a single file script, you can avoid managing
| environments by using a nix shebang: https://github.com/N
| ixOS/nixpkgs/blob/master/doc/languages-f...
| IshKebab wrote:
| Same for me. Mainly due to the packaging fiasco (and to a
| lesser extent, imports).
|
| 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.
| emmanueloga_ wrote:
| Pixi.sh has been great for me so far, it's a single
| binary install that can install Python, conda packages
| and PyPi packages, maybe give it try!
| IshKebab wrote:
| Looks nice but I can't really require the whole team of
| like 100 people to use this quite niche tool.
|
| Python needs an _official_ solution.
| dlahoda wrote:
| poetry with poetry2nix with nix flakes will do magic in
| terms of setup.
|
| if stick with pyright(inference) it is as modern as rust.
|
| python speed increases heavily in all directions.
| IshKebab wrote:
| > poetry with poetry2nix with nix flakes will do magic in
| terms of setup.
|
| I'm sure, but it also sounds like it will take about 2
| weeks of reading manuals and learning Nix before I'll get
| to the same point as Rust and Go start at.
|
| And that's not really an option for big teams, which is
| the only situation where I'm forced to use Python anyway.
| xedrac wrote:
| Because Python falls all over itself in larger projects,
| and is poor at utilizing resources efficiently. It's fine
| for smaller things that don't care about cpu cycles. I
| would much rather use Rust in a large project.
| DrBazza wrote:
| Any non-trivial python is indistinguishable from magic.
| VyseofArcadia wrote:
| 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++.
| JonChesterfield wrote:
| 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.
| ChuckMcM wrote:
| 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." :-)
| tialaramex wrote:
| There's a fun stream where tsoding decides to learn
| Fortran, and the instructions he's working from say to turn
| off implicit typing (ie write "implicit none"). He's
| familiar with modern languages with type inference and with
| C++ type deduction which is a similar idea to full blown
| inference - and so he has no reason to even guess what
| Fortran is going to do without that admonition and you can
| see he's not happy when he finds out.
| pklausler wrote:
| I don't get that at all. Old FORTRAN has a mildly
| confusing feature that is easy to disable. He then got
| upset about the mildly confusing feature that everybody
| now disables. If one wants to bitch about Fortran, at
| least complain about the modern language (which is still
| a horror show of poorly defined and often unportable
| features), not the stuff that has been made obsolete.
| ChuckMcM wrote:
| I was teaching one of the local highschool kids how to
| program in C and they asked "So why does everybody use
| i,j, and k for their indexes in loops?"
| pklausler wrote:
| I only use 'j' and 'k', not 'i ' -- the rarely-used
| letters are easier to search for.
| magpi3 wrote:
| i stands for index. j and k because we can't use i
| anymore, and maybe because they are close together on the
| keyboard
| petsfed wrote:
| 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.
| jbandela1 wrote:
| >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
| celie56 wrote:
| Your recommended json solution was also my first thought
| but if you do not have the ability to easily introduce a
| new dependency then the op is correct.
|
| 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.
| pantsforbirds wrote:
| If you have any problem that isn't vector math, it's
| absolutely awful. Even IO is unpleasant
| VHRanger wrote:
| Let me carefully copy paste my personal stringutils.hpp file
| of string handling routines and I'll be right up to it!
| rightbyte wrote:
| Gotta have those "readfile()", "replace_substr()",
| "split()" etc! I do have a copy paste string util header.
| ..
|
| I really wish there were more string util functions in Cpp.
| I mean C had strtok()!
| PaulDavisThe1st wrote:
| strtok() is one of the most dangerous string handling
| functions in any language!
| rightbyte wrote:
| strtok() is like a hot art student, smoking a cigarette.
| I think I've got to it once.
| PaulDavisThe1st wrote:
| In the C language, you do not get to strtok(3), strtok(3)
| gets to you.
| dkersten wrote:
| 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.
| zerr wrote:
| Often I think that I'm lucky, still working on C++ desktop
| applications.
| tiptup300 wrote:
| I've always wanted to learn C++. I have a great handle on C#,
| making large applications and architectures as well as legacy
| refactoring in C#, and I would love to learn C++.
|
| 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.
| dlachausse wrote:
| I personally recommend starting with Stroustrup's other
| book...A Tour of C++. It really brings you up to speed quickly
| with what you need to know in the language without a lot of
| excess fluff. It's also very up to date compared to other
| books.
| justinhj wrote:
| I love that format, more languages should do it. One of the
| few pure language books I read cover to cover.
| dlachausse wrote:
| I agree!
|
| Another approach I really like are interactive "notebook"
| style language tutorials. Swift Playgrounds is an excellent
| implementation of this.
| MontagFTB wrote:
| Scott Meyers' "Effective C++" series are digestible reads that
| cover the corner cases a modern C++ developer might hit, as
| well as guidelines and best practices to keep from shooting
| yourself in the foot.
| jcelerier wrote:
| Those are starting to be pretty out-of-date. Proper C++23
| code looks nowhere like code from Effective Modern C++
| (published in 2014) just like you wouldn't expect C# or JS
| books from 2014 to be up-to-date with 2024 good practices -
| compare for instance Eloquent Javascript 1st edition (2011)
| and 4th edition (2024) : `let`, `const`, `use strict;` and a
| ton of other things taken for granted today _weren 't there_.
| on_the_train wrote:
| I would be wary of older literature. They're often full of
| classic polymorphism, something that modern c++ has largely
| moved away from.
| ska wrote:
| I haven't read this new edition, but the previous ones are
| pretty decent for the why's and hows.
|
| 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.
| slekker wrote:
| Sorry if it is a bit off-topic.
|
| 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.
| npalli wrote:
| The most complex, demanding and cutting edge computational
| fields - Machine Learning, Artificial Intelligence, Real-time
| multi-user Gaming, High frequency Trading, Rendering/Animation,
| High Performance Computing, Compiler infrastructure (LLVM) -
| are all at the core written in C++ for the most part. There is
| no other option in the foreseeable future as the investment
| needed to rewrite (if you can find the people) is in the $100's
| of billions. So you will need to know C++ if we want to be the
| cutting edge and need extreme performance.
|
| 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++.
| tialaramex wrote:
| > So you will need to know C++ if we want to be the cutting
| edge and need extreme performance.
|
| 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.
| slekker wrote:
| A more extreme version of this would be COBOL right? Even
| _if_ people stopped writing C++ today the amount of code
| that 's already written will last many lifetimes.
| tialaramex wrote:
| Sure, I do not advise people to go learn COBOL either. In
| fact, I never learned COBOL, they were writing COBOL at
| the first place I "worked" as a teenager+ and it was
| clearly not the future.
|
| + in the UK there was a discrepancy between what happens
| to the sort of teenager who exhibits talent and interest
| in an area like writing software, who is sent to just
| _watch_ adults doing that and mostly doesn 't do any
| actual work themselves as "Work Shadowing", versus those
| whose direction seems more... manual who are expected to
| actually go _do_ stuff in the same period, supervised by
| adults of course, but still very much doing the actual
| work, "Work Experience". This seems very obviously
| unfair, although of course as the teenager who wasn't
| expected to actually do much I wasn't complaining at the
| time...
| CyberDildonics wrote:
| I don't even know what you are trying to say here. C++ is
| great to program in and has a fantastic eco system of tools
| and libraries. It is something you can safely base a
| business around.
|
| _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.
| spacechild1 wrote:
| I started because I became interested in graphics and audio
| programming. Audio plugin development in particular is
| completely dominated by C++.
| cuanim wrote:
| Do you have any recommendations for someone interested in
| audio programming?
| spacechild1 wrote:
| Personally, I started by writing externals for Pure Data,
| then started to contribute to the core. Later I took the
| same path for SuperCollider.
|
| 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-...
| cageface wrote:
| The Will Pirkle books are good.
| jandrewrogers wrote:
| There are still some high-performance software domains where
| (modern) C++ is unambiguously the best tool for the job.
| Database engines are a good example of this, they pervasively
| break the compiler's understanding of object lifetimes which
| requires flexibility in the language that C++ can explicitly
| express in an ergonomic way.
|
| 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.
| dmarchand90 wrote:
| Can anyone recommend a good book for numerical c++ in 2024?
| AlexeyBrin wrote:
| Maybe _Discovering Modern C++_ 2nd edition. But check the table
| of content before buying, it may be too beginner level for you.
| tejohnso wrote:
| 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.
| layer8 wrote:
| He uses a custom wrapper library, so not sure how much (if
| anything) of QT proper is exposed.
| pjmlp wrote:
| For the better, with Qt there is QtCreator.
| spacechild1 wrote:
| 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...
| earthnail wrote:
| QtCreator helps with the learning curve as it's a very
| accessible IDE. One of the first IDEs I used in my career.
| spacechild1 wrote:
| Sure, QtCreator is nice and it's actually my IDE of
| choice. I just wanted to point out that it is independent
| of Qt, the library.
| germandiago wrote:
| How it compares to CLion?
| Kranar wrote:
| Qt Creator makes working with Qt a heck of a lot easier in
| a way that working with Visual Studio or vim does not. It
| comes with an integrated Qt form designer, Quick Designer
| for QML, supports Qt's moc syntax out of the box,
| integrated support for Qt Test Integration, native support
| for Qt Assistant and documentation and integration with
| Qt's internationalization tools.
|
| 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.
| iso8859-1 wrote:
| I wonder what Stroustrup thinks about the Meta Object Compiler.
| In a way Qt is its own dialect of C++.
| justin66 wrote:
| He's name-dropped CopperSpice in some of his speeches, so
| he's certainly aware that it's not universally adored.
| UncleOxidant wrote:
| 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 wrote:
| SFML is a graphical library but not a GUI framework/toolkit
| that Qt/FLTK are.
| swatcoder wrote:
| 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.
| aero-glide2 wrote:
| This is the book i used to learn programming 10 years ago! After
| that I never really learnt anything new.. been using the same
| concepts.
| nocoiner wrote:
| Did you use it to learn programming as a novice to the field? I
| have always wanted to learn programming as a hobby, but never
| really found the right entry point. Would you recommend this?
| semanticc wrote:
| I would start with Python instead of C++, if you just want to
| learn a useful tool as a hobby. The official tutorial is a
| good starting point:
| https://docs.python.org/3/tutorial/index.html
| AlexeyBrin wrote:
| For hobby programming, Python is the best (unless you want to
| do web development in which case JavaScript is what you
| want). For Python, a really good book for beginners is
| _Python Crash Course_.
| OnionBlender wrote:
| My problem with newer C++ books is that all of my projects are
| stuck using C++17.
| nicce wrote:
| If they are purely your projects, then it is just a matter of
| will :-D
| OnionBlender wrote:
| I mean the work projects I work on. Mostly Android NDK stuff
| that uses C++17.
| zerr wrote:
| Are there any university lectures/videos based on this book?
| chuckadams wrote:
| 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.
| pif wrote:
| You learned to program on Windows, didn't you?
| marcosdumay wrote:
| lpsiNo, spbI uiOnly lpwAdopted iThe spdwStyle usLater.
| chuckadams wrote:
| 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()
| HarHarVeryFunny wrote:
| 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.
| culi wrote:
| Conversely,
|
| We write code once, but read it many times, so longer names
| seems like a poor efficiency choice.
| HarHarVeryFunny wrote:
| What's the logic of that though? Longer more descriptive
| names (self-documenting code) help readability, not hinder
| it.
|
| 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.
| nuancebydefault wrote:
| Longer names are harder to read. Think about any math
| formula. Does energy=mass * math::powerf(speed_of_light,
| 2) read more fluently? Context matters. Make sure the
| context is ways clear and code is written there where it
| belongs. Then names can be shorter while being readable.
| HarHarVeryFunny wrote:
| I'm not sure that's a great example. Of course e = mc^2
| is so iconic and well known that most people know it, and
| will probably even perceive it as a whole. Once you
| recognize it then no need to explain what e, m and c are.
|
| However, most code is not that obvious, and in the real
| world you're probably not looking at one mystery line of
| code who's function becomes obvious by context - you are
| more likely looking at entire functions or blocks of
| code, maybe without comments, trying to figure out what
| is going on. Try inheriting 10K of mostly undocumented
| code, and then you'd probably be a lot more grateful that
| the original author used descriptive names and comments,
| even though he knew what it all meant when he wrote it.
| Kranar wrote:
| >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.
| HarHarVeryFunny wrote:
| > This to me seems like a cargo cult justification, where
| you've heard the argument ...
|
| 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 ...
| Kranar wrote:
| I am not saying you are cargo cult programming, but being
| a cargo cult programmer has nothing to do with seniority.
| There are plenty of people who have been programming for
| decades who blindly follow rules because that's how they
| learned things, that's what they were taught is good
| practice, and they never bothered to question it, reflect
| on it, and they go along with it because of cultural
| reasons rather than because they have a genuine
| understanding of the principles.
|
| >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 ...
|
| But what lesson did you learn? That long names are better
| than short names, which is what I called cargo cult
| programming and an instance of mixing up the metric for
| the principle? Or did you instead learn that descriptive
| names are better than non-descriptive names?
|
| If it's that long names are better than short names, then
| by all means continue using std:: everywhere. If instead
| it's that descriptive names that communicate purpose or
| intention or actual information are better than non-
| descriptive names, then having a bunch of std::
| everywhere doesn't do much of anything to help
| readability, it just adds noise.
|
| Now people can and do justify the use of std:: but I've
| never heard it on the basis of making code more readable.
| There is nothing self documenting about a bunch of names
| that all share a common prefix.
|
| And this doesn't even touch on how ironic it is that std
| is itself non-descriptive jargon that is an abbreviation
| of standard, but I am almost certain that if everyone had
| to liter their codebase with standard:: everywhere, no
| one would think twice about what the right thing to do
| is.
| HarHarVeryFunny wrote:
| > But what lesson did you learn? That long names are
| better than short names, which is what I called cargo
| cult programming and an instance of mixing up the metric
| for the principle? Or did you instead learn that
| descriptive names are better than non-descriptive names?
|
| Do you always suppose that the people you are talking to
| are morons and cargo-cultists?
|
| Rhetorical question - have fun.
| Kranar wrote:
| I like to present questions to people to justify their
| position so that others reading the advice can better
| evaluate it, understand the reasons and make a more
| informed judgement on it.
|
| I am also principled in critiquing an argument and never
| critiquing a person. I said that the advice you gave is a
| form of cargo culting, but I also said in the very first
| sentence that "I am not saying you are cargo cult
| programming".
|
| I don't think there is anything wrong with getting into
| the subtleties of whether the advice is what you
| originally said it was, which is that longer names are
| better than shorter names, or whether the advice you
| learned was that descriptive names are better than non-
| descriptive names.
|
| I think the subtlety between those two statements is not
| being appreciated and without a clear distinction other
| people may read that advice and take away the wrong
| conclusion.
|
| Take care.
| winwang wrote:
| Yep, although I do like not having clashing names.
|
| But I mean... somehow every other language solved this.
| Jtsummers wrote:
| > 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?
| chuckadams wrote:
| It's certainly not every other language, but Unison has a
| novel approach to solving the problem of name clashes:
| function names are just local aliases for a content hash of
| the function's AST. Compiling involves replacing function
| names with those hashes, and putting the names back is a
| matter of pretty-printing. I'm sure there's an arsenal of
| footguns lurking in Unison's system, but for sure it opens
| up interesting opportunities (distributed code becomes
| "grab this function out of cache").
| Jtsummers wrote:
| Does that actually solve name clashes? If I have two
| functions compiled at the same time: def
| foo(n): return n + 2 def foo(n):
| return n * 2 foo(3) # which one is called?
|
| (I don't know Unison syntax so using Python for the
| example)
|
| It's still a name clash at compile time.
| chuckadams wrote:
| TBH I've only dipped my toe into Unison, but I don't
| believe it would let you re-bind the same identifier in
| the same scope in the same compilation unit. It's more
| that `foo(3)` becomes a call to the hashed version
| `#e0ca5f(3)` forevermore. Once a function has been
| compiled, it doesn't care what the names of any functions
| it uses are afterward, until you explicitly recompile
| them to use the new names. So it really has more to do
| with preventing versioning conflicts ... others can
| explain it much better than me, sorry.
| zengid wrote:
| I hear that once c++ modules lands this shouldn't be
| controversial anymore, right?
| deeznuttynutz wrote:
| 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.
| ben7799 wrote:
| 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.
| uwagar wrote:
| why not P3 instead of PPP3?
| CSMastermind wrote:
| A new version is extremely exciting.
|
| Even 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.
| bluedino wrote:
| Why does Bjarne only sometimes use a space after _#include_?
| #include<stdint.h> #include<list> #include <map>
| #include<unordered_map> #include <set>
| #include<memory> #include <algorithm>
|
| https://www.stroustrup.com/PPPheaders.h
| lstamour wrote:
| Could be missed if there was a mix of typed by hand and auto-
| inserted by IDE headers, plus maybe a setting that collapses
| (folds) imports by default... and clang-format wasn't run on
| save? ;-)
| aquir wrote:
| Great but I am unable to find an IDE or compiler that supports
| C++ 20 and every one of them complains about import std;
|
| Any recommendations?
| xdavidliu wrote:
| I ran into this the last time I tried reading this book. It's
| supposed to be for beginners; how would a beginner get around
| this?
| heyoni wrote:
| CLion seems to support it through a mixture of clangd and its
| own parser:
| https://www.jetbrains.com/help/clion/c-support.html#cpp-
| stan...
| xdavidliu wrote:
| 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++")
| humanrebar wrote:
| 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/
___________________________________________________________________
(page generated 2024-04-19 23:01 UTC)