[HN Gopher] Embracing Modern C++ Safely, Book Review
___________________________________________________________________
Embracing Modern C++ Safely, Book Review
Author : ibobev
Score : 95 points
Date : 2022-05-30 14:08 UTC (8 hours ago)
(HTM) web link (www.cppstories.com)
(TXT) w3m dump (www.cppstories.com)
| blinkingled wrote:
| Is any new code being written in C++? Apart from adding to
| existing C++ based projects like Chromium and maybe supporting
| legacy trading/financial services code bases what else is C++
| being used for where all the modern new features would be
| helpful?
|
| I haven't seen any job postings needing C++ lately but I am sure
| some niche jobs exist.
|
| Feels like instead of learning the complexities of modern c++
| people might just be better off using Rust or any of the other
| safer programming languages for new projects.
| roxaaaane wrote:
| There are 80,000 jobs mentioning or requiring C++ and 4000
| mentioning or requiring Rust. I understand more "modern"
| startups will tend to pick Rust but saying you "haven't seen
| jobs needing C++" is a plain lie. source:indeed.com
| aaaaaaaaaaab wrote:
| tfigment wrote:
| I was kind of hoping this was updated Modern C++ Design by Andrei
| Alexandrescu. That was my favorite C++ book and at least I
| thought it didn't use the STL in Loki at all. It was the better
| templating design though heavily at the mercy of compilers at the
| time.
| SuperV1234 wrote:
| Somewhat tangential, but Andrei Alexandrescu was fundamental
| for this book -- he reviewed the entirety of it, providing a
| lot of suggestions and improvements, and also helped write a
| few sections :)
| Iwan-Zotow wrote:
| Title itself is an abomination
| rob74 wrote:
| My mental image of C++ is a tool which is great when used by an
| expert, but has lots of sharp edges which can cut you if you're
| not careful - so not something I would apply the verb "embrace"
| to...
| sgeisenh wrote:
| Collaboration on a C++ codebase can be interesting. One of the
| most common approaches that organizations use is to choose a
| subset of the language and discourage committing code that
| doesn't conform to that subset.
|
| This limits the sharp edges and in particular makes it easier
| to identify where they might exist. Perhaps the most common
| rule is the prohibition of exceptional control flow. This can
| seem really limiting at first, but encoding the possibility of
| errors using the type system and forcing callers to handle
| errors explicitly is really powerful.
| agumonkey wrote:
| I think I've seen stroustrup say that in a few talks.
| colejohnson66 wrote:
| If I have to use a subset of a language to avoid shooting my
| feet, why not just use a language without footguns?
| jandrewrogers wrote:
| Because different types of software make good use of
| different subsets of C++. A "footgun" for one codebase is a
| "high-leverage feature" for another code base. The subset
| of "no footguns" C++ that is common to virtually all
| applications probably asymptotically converges on the empty
| set. A feature of C++ is that you can precisely select an
| optimally expressive subset for most applications instead
| of being forced to write code in language that clearly
| wasn't designed with your use case in mind.
|
| Having a lot of tools in your toolbox doesn't necessitate
| using all of them in inappropriate contexts. I don't try to
| hammer a screw just because I own a hammer.
| deltaonefour wrote:
| This analogy sounds nice but is deceptive. The problem is
| there's no place where a foot gun is appropriate. I need
| a toolbox for screwing things so I get a screwdriver
| toolbox, but in that toolbox is a foot gun designed to
| blow my foot off. Why? What context is that foot gun
| appropriate? Should I put it in the hammer toolbox? C++
| has footguns everywhere and there's no context where many
| of those footguns are appropriate.
|
| The other thing with C++ is the complexity. The toolbox
| is so jam packed full of millions of tools I have
| basically can't comprehend the full ecosystem and how
| everything works. Additionally I pick one tool and that
| single tool itself has like 20 different ways of being
| used with a bunch of edge case gotchas.
| arinlen wrote:
| > _If I have to use a subset of a language to avoid
| shooting my feet, why not just use a language without
| footguns?_
|
| Because it has absolutely nothing to do with footguns.
|
| The main factors in picking subsets, beyond personal tastes
| on coding styles and office politics, boil down to a)
| introducing exceptions in legacy code, and thus the need to
| revalidate what is otherwise solid code, b) not be forced
| to deal with the complexity of template metaprogramming
| when the value it adds back is negligible.
| faitswulff wrote:
| Not every project can be a greenfield project.
| deltaonefour wrote:
| I agree but C++ is so ingrained that tons of greenfield
| projects end up using C++ because of libraries and
| because too many people are used to it.
| ncmncm wrote:
| In other words, C++ is too useful not to use a lot.
| loeg wrote:
| There are lots of other advantages and disadvantages to any
| given language. You're right that this is a mark against
| C++, but wrong in the assumption that it (always) outweighs
| all other considerations (performance, familiarity,
| compatibility with existing C++ codebase, portability to
| odd architectures). (Personally, I don't like C++ and
| prefer Rust. But it is also reasonable to choose C++.)
| jstx1 wrote:
| Because that subset can still be better at solving your
| problem than those other languages - it could be faster,
| more mature, better at solving certain problems, you can
| leverage existing ecosystem etc.
| Koshkin wrote:
| This is exactly true. Noone in the C++ world uses all of
| C++ in their project. It is a multi-paradigm language,
| and you are free to choose one (or a few) of the
| paradigms and follow it throughout the entire project.
| For example, you can choose to base your project on
| virtual functions and interfaces, or you can choose to
| employ static polymorphism instead. Remarkably, even the
| C++ standard library, for all its intricacy and
| complexity, does not use all of C++. Also, it is useful
| to see C++ as two languages, one for library developers,
| and one for developers of applications.
| froh wrote:
| Isn't that focus on a core c++ feature subset and coding
| patterns also the idea behind the "c++ core guidelines"?
|
| https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines
| tialaramex wrote:
| Sure, the effect of such guidelines, including the "Core
| Guidelines" is to further shatter the language into
| effectively incompatible dialects while not really solving
| anything.
|
| One of the book's authors actually proposed work to get C++
| to a place where C++ 20 could begin actually _abolishing_
| the things everybody agrees you shouldn 't do, Vittorio's
| "Epochs" proposal. https://vittorioromeo.info/index/blog/fi
| xing_cpp_with_epochs...
|
| But the preference for C++ 20 was to add yet further stuff.
| I believe that, unwittingly, the C++ 20 process sealed the
| fate of the language in choosing to land features like
| Concepts but not attempt Epochs, I'm not sure it was
| actually possible, but if it wasn't possible in 2020 it's
| not going to be any easier in 2026 and it's only going to
| be more necessary.
| ncmncm wrote:
| This is of course false.
|
| The active subset is always the set of features not
| supplanted by the latest Standard supported by tooling in
| use. Anything newer is safer and nicer than old crap, so
| there is no temptation to stick to old crap, except among
| people who have elected not to learn anything new. Those
| are typically approaching retirement anyway.
| [deleted]
| jmspring wrote:
| Computer science programs used to teach variations of C/C++.
| Last I checked where I went as well as talking to junior
| engineers I have worked with. You can get through a whole CS
| program at a dop 50 university without touching the language.
|
| There have been debates here about C/C++ being "dangerous". And
| it can be, if you don't know how to use it. I recall
| discussions where doing in-line assembly in C had a similar
| discussion.
|
| It doesn't take being an "expert". It does take "understanding
| what you are doing" but that same thing applies regardless of
| the language/tool/etc.
| criddell wrote:
| The depth of what you want to understand with C++ is
| sometimes pretty deep though. I'm thinking about things like
| lvalues, rvalues, const vs constexpr, etc...
| garren wrote:
| Wouldn't you say that "understanding what your doing" applies
| a little more to C/C++ than many other languages/tools/etc?
| Both Microsoft[0] and Google[1] have established that ~70% of
| the defects they encounter in their flagship products and
| systems are memory-related, and generally attributed to the
| "dangers" of the underlying language: C++
|
| It seems significant that, given that the individuals working
| on these projects are professionals, experts by some
| definition, they too are encountering issues related to the
| sharp edges of these languages. Issues that have wide ranging
| implications.
|
| In light of that, doesn't saying that "understanding what
| you're doing" is all it takes to productively and safely use
| a language like C/C++ seem simplistic? Even the experts are
| getting it wrong.
|
| I took a couple C++ classes in college. I've worked on both
| desktop and backend C++ systems in both C++98 and '11. It can
| be a difficult language, it has more than its share of
| footguns, it definitely helped me appreciate other languages
| that don't have similar issues.
|
| [0] https://msrc-blog.microsoft.com/2019/07/16/a-proactive-
| appro...
|
| [1] https://www.chromium.org/Home/chromium-security/memory-
| safet...
| nyanpasu64 wrote:
| I prefer Rust's approach to spatial memory safety over C++;
| it doesn't get in your way and it's good at preventing out-
| of-bounds access at a low performance cost. I also like
| Rust's approach to threading over C++; in a world where
| data races are undefined behavior and the typical C++
| threaded program (both from before and after C++11's memory
| model) is an entangled UB-filled mess impossible to
| refactor, Rust's Send/Sync and &/&mut is needed discipline
| to organize programs. I'm unconvinced by Rust's insistence
| on temporal memory safety (the compiler follows fixed
| rules, it takes unsafe code to teach it about things like
| scoped threads) and "aliased xor mutable" (which rules out
| even many correct C++/Java architectures and requires
| either dangerously tricky unsafe code or needless rewrites
| in safe code, and optimizes for local reasoning at the cost
| of flexibility and expressiveness, which is sometimes a bad
| tradeoff, and SB is a needlessly strict nightmare with no
| equivalent to unique_ptr supplying RAII deallocation
| without noalias semantics). Though it _is_ wise to be
| _cautious_ in C++ around objects with self-pointers (unsafe
| to move) or aliasing member pointers (tricky lifetime
| constraints).
| oconnor663 wrote:
| When the problem is "understanding what you are doing" it's
| not so bad. But often the problem is more like "understand
| what everyone around you has done". If they shared an object
| across threads, then you can't do mutation without a lock. If
| they retained a reference into your vector, then you can't
| grow it. It's this sort of invisible UB at a distance that
| gets so hard to deal with as projects get larger, even
| between experts.
| Koshkin wrote:
| Hence this book.
| deltaonefour wrote:
| That's not even the right analogy. I think of it more as a
| rotary phone dial. It's old and overly complex and poorly
| designed. It's still in use for legacy reasons and because you
| have tons of these "experts" who have invested so much time and
| pride into it they actually can't really accept the fact that
| legacy is the only reason why C++ is still here.
|
| The problem is the nature of programming makes it so that once
| a language embeds itself into the infrastructure it's hard to
| remove or upgrade. Very similar to how most of the front end
| world is stuck with javascript.
|
| JavaScript as ugly as it is, is nowhere near the monstrosity
| that C++ has become though.
| Animats wrote:
| The trouble with "Modern C++" is that nothing gets deleted from
| "Classic C++". Too much legacy code. They're trying to compete
| with Rust while remaining backwards compatible. That generates so
| many special cases that you need a 1300 page book. Learn to
| embrace the pain.
|
| And yet converting code to Rust is _hard_. It is very tough to
| convert object-oriented C++ code to Rust. The models are too
| different.
| Sakos wrote:
| Unfortunately, the real world often gives us constraints that
| we can't change and we have to work around. We should
| absolutely use Rust or other "safer" languages where we can.
| But if we can't, for whatever reason, it makes sense to try to
| make the best of the hand we're dealt. That means regardless of
| what new developments are made in other languages, it's
| necessary to figure out how to use existing tools/languages
| like C++ safely.
| pjmlp wrote:
| Not when it is COM-oriented C++ code, which is based on
| interface (aka traits) inheritance, or the IPC mechanisms used
| on Android/Fuchsia.
| ncmncm wrote:
| Anybody still coding to COM has asked for all the pain they
| experience.
| UmbertoNoEco wrote:
| Writing as someone just learning Rust (knowing more C++) I
| think a comprehensive Rust book would be in that scale too
| (+1000 pages).
|
| > Learn to embrace the pain.
|
| Judging by how much I suffered just to try to implement a sqrt
| function generically I think that is not an exclusive C++
| thing.
|
| > And yet converting code to Rust is hard.
|
| Exactly, that is why many many projects will remain in C++ for
| a long long time.
| ncmncm wrote:
| All projects in C++ will remain C++ forever.
|
| Some projects will be coded in other languages, and stay in
| those languages. Wherever that language fizzles, the project
| will too.
| arinlen wrote:
| > _The trouble with "Modern C++" is that nothing gets deleted
| from "Classic C++"._
|
| This is not exactly true. For example, with the introduction of
| smart pointers, manual memory management is kicked out of C++'s
| happy path. This makes code far simpler to reason about and
| safer. Sure, you can still use new and delete, but since C++11
| you better have a very good reason to use those.
|
| Nevertheless, it doesn't make sense to complain about not
| deleting stuff from C++ when a) until recently C++ was
| repeatedly criticized for having an extremely spartan standard
| library, b) since C++98 basic features were added to C++ such
| as support for parallel and concurrent programming, c) there is
| no feature that gathers anything resembling a consensus on beig
| worth taking out of the standard.
|
| I'd add that pseudo-standard libraries for C++, such as Boost
| and POCO, have been popping up and growing in both scope and
| adoption. This reflects a clear need felt by the C++ community
| to increase the scope of it's standard components.
| Animats wrote:
| There are too many APIs that still want raw pointers.
| arinlen wrote:
| > _There are too many APIs that still want raw pointers._
|
| Irrelevant. C++'s smart pointers deal with ownership and
| life cycle management. You can still pass raw pointers to
| objects managed by a smart pointers.
|
| The only exception is when you're dealing with a framework
| which already handles life cycle management, such as Qt.
| Nevertheless, even Qt offers its own smart pointers suite.
| UncleMeat wrote:
| > You can still pass raw pointers to objects managed by a
| smart pointers.
|
| Not if the API is taking ownership and you want your
| program to be correct. This happens _far_ more often than
| dealing with something like Qt.
| cjaybo wrote:
| Even if they want to take ownership, smart pointers allow
| the semantics to be expressed clearly and in a safe manner.
| Koshkin wrote:
| There's nothing wrong with using a raw pointer as an
| argument of a function. In this context this is usually
| equivalent to using a reference. What _is_ wrong, in fact,
| is passing, instead, a unique pointer (by reference,
| necessarily) or, even worse, a shared pointer (by value)
| when there is no need for sharing.
| Koshkin wrote:
| > _They 're trying to compete with Rust_
|
| I honestly think it's the other way around.
| ncmncm wrote:
| Yes. Rust needs radically more use not to end up fizzling
| like myriad languages before it. But its stalwarts are
| hostile to measures to make it easier for people to pick up,
| even easy ones that do not alter the language at all. It
| takes a special dedication to overcome barriers that most of
| the people it must attract lack.
|
| It was meant to supplant C, but C users, as a rule, are
| defined by seeing a thousand other languages go by and not
| jumping. So Rust mostly picks up discontents from other
| languages, including Java, Go, and, yes, C++.
|
| The danger in appealing to discontents is that they are
| likely to jump ship for the next shiny thing.
| oncewas wrote:
| I mean I get what you are saying about how old stuff
| doesn't have adoption issues. But, rust is a pretty unique
| paradigm. The safety guarantees it offers aren't found in
| other languages without garbage collectors.
|
| Rust is boring and technical. Boring in the "it just works
| and when it doesn't it's not hard to figure out why" way.
| You didn't say this, but for others passing by, it would be
| a mistake to view rust as a "shiny thing". People use it
| for a reason, barring syntax entirely.
| W0lf wrote:
| Given that I am working professionally with C++ (meaning I earn
| money by writing code in this language) I find it remarkable,
| that I appreciate and actually think it's a useful book for my
| daily work. 1300+ pages of detailed language features just to
| somewhat get by and feel sufficient competent that my code does
| what I intended to do.
|
| Looking behind my back there is a shelf of another 30+ books full
| of C++ (Meyers, Sutter, Alexandrescu, Langr, Feathers,
| Stroustrup, Lakos etc) that I have read page to page. However, I
| am certain that any sufficient C++ developer can embarrass me by
| showing me a corner of this language I have never experienced
| before. It just never stops. The things I have to keep in mind
| while coding a solution for the actual problem at hand can be
| astounding.
|
| But then, I really like coding in it as there are these rare
| cases when I'm coming up with an elegant and straight to the
| point solution. I think I have some kind of Stockholm love-hate
| relationship with this tool of choice.
| bcrosby95 wrote:
| Alexandrescu's books are what caused me to "nope" out of C++
| and jump ship to Java.
|
| And when my friend starting working at Google (in C++), I gave
| him my pile of books.
| ncmncm wrote:
| It is not the language for everyone. But the stuff in
| Alexandrescu's book is more for people showing off than for
| people doing useful work.
|
| Most of the tricks resented there are obsolete, supplanted by
| straightforward core language features.
| k0k0r0 wrote:
| Not a professional here - by my own standart at least - however
| I also program in C++ for a living (among other languages).
|
| Definitely Stockholm-Syndrom in my case. Was the first language
| in which I was forced to work on some larger codebase. Since
| then I can't take the complexity of any other object-oriented
| language serious. All of them are basically a subset of C++.
| andi999 wrote:
| How relevant was Lakos book in your opinion?
| W0lf wrote:
| An opinionated thorough demonstration on how to write C++ at
| scale. I didn't agree one all aspects, though I have to admit
| it was the first book on C++ that clearly stated _how_ to
| actually design stuff both on a physical as well as on a
| logical level. Something which most other books on C++ won't
| get into. All that being said I think it was pretty relevant
| for medium to large codebases
| ncmncm wrote:
| Not at all.
|
| It has exactly one obviously useful piece of advice: don't
| make circular dependencies between libraries. In practice,
| that means organizing in layers.
|
| Most of us don't depend on many libraries where the authors
| of the libraries know one another, so it is easy to follow,
| even by accident.
|
| It has lots and lots of obsolete advice, though.
| gigatexal wrote:
| At what point does a C++ programmer like yourself just switch
| to something that advertises safety but also C like
| performance? At what point does it get so difficult to write
| robust, "safe" C++ that one switches languages? How necessary
| is all this safety, even? (Doh! Of course it's necessary for
| hardening your software against bugs and making the overall
| ecosystem safer).
| ncmncm wrote:
| Much of what can usefully be written in C++ cannot be
| expressed at all in other languages, Rust included. Thus, for
| serious users, switching would mean a big step down.
|
| Most of the powerful, unique features are there to help
| encapsulate semantics in libraries, enabling libraries to
| adapt automatically to use circumstances without loss of
| performance. As a result, libraries in C++ can be more
| powerful and useful.
| snovv_crash wrote:
| The complexity of C++ lives primarily in the fact that it is
| almost entirely backwards compatible all the way back to the
| late 1980s, and mostly compatible all the way back to K&R C.
|
| Modern C++, when you stick to the new idioms (RAII, range
| loops, auto lambdas etc) is almost as compact and succinct as
| Python with type annotations. One of the biggest differences
| is readability is that the standard library is not "batteries
| included" so people roll a lot of stuff themselves.
| maccard wrote:
| There's absolutely nothing of sustinence in this book review -
| they give the book 5/5 despite having not actually read it, and
| the only comments on the individual topics are on the length of
| the chapters. This is really a terrible review.
| Sakos wrote:
| I'm not sure if you stopped too early or if you have a grudge
| against the author or what.
|
| > I'm still reading this book, and I haven't read all the pages
| (1300+ pages!). Yet, I've seen all of chapters, read half of
| them and picked those related to my recent work, tasks, or blog
| posts. I'm impressed with the level of detail and the quality
| the authors put into this material. The book has become my
| primary "reference" for those C++11/14 parts.
|
| With further detail below that.
| avgcorrection wrote:
| This is an elementary school book analysis-level review.
| [deleted]
| Koshkin wrote:
| 'substance'
| bombcar wrote:
| Sustenance could also work - as a review it's like a meal
| made of cellulose. Lots of action but no energy.
| photochemsyn wrote:
| If I had cash to burn I might keep buying computer programming
| books, but as it is it's just become easier to use Google to
| research compsci topics in every area. For example, if I get
| confused about constexpr functions in C++ I can just Google with
| upload dates restricted to the past four years and up pops, for
| example, a nice learncpp page with just about everything I need
| to know for basic uses.
|
| That said, I downloaded their sample pdf and the nice thing is
| the code they present is very well commented and so it's easy to
| read. They seem to take a 'read the code to learn the subject'
| approach, which I appreciate. Note that it takes a slightly
| conservative approach:
|
| > "Only the passage of time can distill the programming
| community's practical experience with each feature and how well
| it fared, which is why this book discusses features added up to
| C++14, even though C++20 is already out."
|
| Maybe I'm missing something but they don't seem to offer the book
| as a searchable PDF? There seems to be a Kindle edition and
| paperback only. Worried about piracy or something? Otherwise it
| might be a useful reference, I guess.
| stu2b50 wrote:
| They're not really for the same purpose. The internet is great
| for finding documentation and reference material, but for
| larger, cohesive concepts like the book this post is about is
| on, especially since it's somewhat fringe, you will likely only
| be able to find bad blog spam on medium, which will be far
| inferior in quality.
| criddell wrote:
| Books are great for when you don't know what you don't know.
| Scott Meyers' _Effective C++_ books were hugely valuable to me
| for that reason.
| egl2021 wrote:
| Same for me. Back in the day I learned C++ by reading each
| item in Effective C++ and studying Ellis and Stroustrup until
| I (almost) understood everything that Meyers mentioned in the
| item. It was slow going...
| SloopJon wrote:
| > Maybe I'm missing something but they don't seem to offer the
| book as a searchable PDF? There seems to be a Kindle edition
| and paperback only.
|
| The InformIT page linked from the review has (I'm in the US):
|
| * book for $64
|
| * ebook as ePub, Mobi, and PDF for $51
|
| * book + ebook bundle for $86
|
| The sample PDF is searchable, so I presume the full PDF is as
| well.
|
| If you're looking at the Amazon listing, then no, I don't
| expect Amazon to offer PDFs instead of, or even in addition to,
| a Kindle edition. Oddly, the Kindle edition is more expensive
| than Amazon's paper copy, or InformIT's ebook.
|
| Based on the sample, this looks like a nice book. It seems to
| have Meyers-like advice in a more concise, reference-style
| presentation.
|
| It's a slight concern that all four authors are from the same
| department of the same company. I don't know anything about
| Bloomberg Development Environment, but I would be skeptical of
| a similar offering from, say, Google.
| dmlorenzetti wrote:
| Worth noting that InformIT currently has a sale running.
| Through end of 31-May EDT, use code SUNSHINE to get 50% off
| when you buy two books or ebooks.
| photochemsyn wrote:
| Thanks for that info. Definitely this looks like a useful pdf
| to have on hand to look stuff up with a quick search
| (carrying around a 1300 pg book is out of the question). I
| really like the code samples on the sample.
| sigzero wrote:
| From the book page:
|
| Includes EPUB, MOBI, and PDF
| [deleted]
| selimnairb wrote:
| Experienced Python, C, and Java programmer here (am also learning
| Rust on the side). Recently picked up a C++ project at work that
| targets C++14. I know caveman C++ from my time at University 20+
| years ago. My god is there a galaxy of complexity in modern C++.
| I get the need for some of it (e.g., smart pointers), but for new
| projects, I can't see a good reason not to use Rust at this
| point.
| oncewas wrote:
| No joke. I used C++98 for a job a while back and got
| comfortable with it, I asked "hey why don't we use c++14"(this
| was years ago). The answer was basically, modern c++ is too
| complex to keep code bases sane without spending a week writing
| rules and having dozens of meetings, so they opted for the 20
| yr old version.
|
| More recently I've learned rust. I haven't missed c++ at all.
| Even the more modern stuff I've learned later on...
| bobbyi wrote:
| Why is "final" an unsafe feature?
| ncmncm wrote:
| It is not.
| rad_gruchalski wrote:
| Uhh, reminds me that I need to read it. Got it recently and
| looking forward to the content. The review makes me even more
| hungry!
| lain98 wrote:
| I cant afford these books.
| arunc wrote:
| Someone needs to write a book with the list of books to learn
| C++ the correct way. It's definitely unaffordable.
| jb1991 wrote:
| There is a community-curated list of the best C++ books on
| Stackoverflow.
| UmbertoNoEco wrote:
| https://stackoverflow.com/questions/388242/the-
| definitive-c-...
|
| One of the good things of the language being so all and
| pervasive is that there is a lot of very good learning
| materials.
| Koshkin wrote:
| Some time ago it occurred to me that the price you pay in time
| and effort absorbing the material from a book like this one is
| usually incomparably higher than the price of the book itself.
| [deleted]
___________________________________________________________________
(page generated 2022-05-30 23:01 UTC)