Hacker Newsnew | past | comments | ask | show | jobs | submitlogin
Google's C++ Class (developers.google.com)
272 points by hamid914 on March 5, 2018 | hide | past | favorite | 56 comments


Does anyone have any recommendations for learning to write modern, idiomatic C++? I used C++ in college for data structures and algorithms, so I have some familiarity with the basics. But we were mostly restricted to using C++98, and I'm not sure what the best practices look like these days with the changes introduced in 11, 14, and 17.


Effective Modern C++ by Scott Meyers is a good book that I've been supplementing with google searches. It goes over the main new features in '11 and '14 you would want to know.


+1 for this book. Also, if your company can afford it, having Meyers or Sutter coming on site to give a day or two lecture to a group about Modern C++ is worth it. They both have great handout material, give great lectures/presentations and are very approachable with (even idiotic) questions.

(disclaimer: I am an unattributed - due to company policy - interviewee for Meyers Effective Modern C++)

edit: grammar


Scott retired in 2015; I don't know if Scott is still active in terms of lectures/presentations:

http://www.aristeia.com/


Jon Kalb has told on CppCast that Scott is doing a presentation at CppNow, but totally unrelated to C++ (presentation skills workshop).

http://cppcast.com/2018/03/jon-kalb/


Aw, damn. It's been before 2014 I last saw him in person, so I have no idea. It's a shame, because he is a great presenter with an infectious energy about him that I found really engaging.


I can confirm that this book is a great starting point, having undertaken a similar project last year. Off the top of my head, the biggest change is move semantics, along with smart pointers. Once you have those concepts down the other pieces are comparatively quick to pick up.

I've always liked C++, but I think it's become a much more enjoyable language to use in the last decade.

Oh, while you're at it, check out the Passkey pattern[0], which is a nice way to avoid overuse of friend classes.

[0] https://stackoverflow.com/questions/3324248/how-to-name-this...


It's a good book, but I find his use of his good writing skills to try to smooth over the many terrible parts of the language a little irksome.



I am not an experienced C+++ programmer. That being said, I found Marc Gregoire's book to be pretty good. https://www.amazon.com/Professional-C-Marc-Gregoire/dp/11188...

The 3rd edition covers c++14. New version coming out in April covers C++17.


The super FAQ at by isocpp is very good. https://isocpp.org/faq




I found this a good (if short) primer on the latest features: https://www.amazon.com/11-14-Tips-Understand-novelties/dp/15...


I really like the idea of google open sourcing stuff but it seems like they always do it in the worst way possible.. Maybe I'm looking at the wrong projects. For example WebRTC is buried in Chromium (so is QUIC iirc) and to build either of those things it's a lot of freaking work because you have to figure out Google's build system with the documentation doing its best to prevent you from figuring it out.


That and Google is really bad at removing dead code from OSS projects. Looking through projects like Omaha is a pain.


I don't think that's true in general. Google released some widely used open-source projects like Kubernetes, Tensorflow, Android, Go, Chromonium and Angular.


Android is one of the poster childs how bad Google documentation is scattered all over Stackoverflow, Google blogs, Medium articles, outdated entries in official documentation.

Then the multiple revisions of build tools and plugins, support library releases with multiple issues on release day, breakages on Android Studio in spite of several months in beta.


AOSP in particular has very little documentation. When I was learning it the only thing I could find was a draft of an O'Reilly book. That, or reading the source code for the build system.


I'd say it's generally true with their native projects (C/C++).

With their higher level stuff, they do a lot better.


Don't forget protocol buffers !


Is there a list of all classes available under developers.google.com ? I could not find one from the front page. Edit: found it, https://developers.google.com/products/#a


I was hoping this was a class in the object-oriented language sense, and that somehow you'd use this class to instantiate a C++ in your program. Oh well—one can always dream.


I was hoping it referred to a singular, monolithic C++ class in use by Google, to which any new C++ code must be added.


We’ve adopted the monoclass architecture at our startup after reading about how well it works at Google.


It's pretty convenient in the embedded world too because it let's us minimize the size of the global initializer table our compiler outputs.


Yes, but do you have the 50 engineers working on supporting tools for the monoclass architecture?


You've heard of monorepo? Well check this out!


Wait, there are other ways to write C++ programs?


Really cool that Google is open sourcing this (as well as some of their other classes, like the machine learning one).

Back in the day when I was learning to code, one had to trudge through a tome of esotericism after spending hours setting up your compiler. The snow was waist deep and uphill both ways. Seriously tho, this is great. My kids are now learning to code and the availability of great resources makes a huge difference.


I'm surprised that they don't go too much into good practice and style; these are heavily enforced in Google's code-bases. I would expect to see things like references and smart pointers, raw pointers are typically avoided as much as possible to avoid all the fun problems that come along with them.


Sure but naked pointers and manually managing allocation and deallocation force you to learn about how memory works in C++! Abstracting that stuff away is great for safety, but maybe less great for learning fundamentals.


Looking at the Getting Started section... Is this really the best way to write text out to the console in C++, or is it just traditional?

    cout << "Hello World!" << endl;
It seems like something a bit simpler, readable and predictable would be better for beginners and/or experienced devs alike. I look at that and wonder where did cout come from? Is << a heredoc or some sort of pipe indirection, or am I bit-shifting? And is endl a keyword? Does it always follow cout? Is this like a Pascal endif? Oh, it's basically just a newline. What's wrong with just "\n"? I think C++ devs purposefully make their language as obtuse as possible.

Maybe NOT starting with streamio and operator overloading might be a more modern way to start teaching the language?


Anecdotally, beginners have less issues with this than trying to remember printf format strings.


> Oh, it's basically just a newline. What's wrong with just "\n"?

Not all platforms use “\n” for a new line.


The std::stream will translate '\n' to what's required for the underlying platform, so it is a perfectly portable way to terminate a line.

What std::endl really does is flush the internal stream buffer if any.


For beginners I didn't have trouble with `cout` and `<<`. Just teach that that's how you print without going in details.

This is more a problem with folks with experience in other languages, who know bitshift or heredoc syntax. But those can be teached in a more advanced way.


> I look at that and wonder where did cout come from?

This is the biggest issue with this. STOP TEACHING “using namespace std;”. This is bad, bad, bad, and it sucks.


I'm surprised that in their unit tests category, they are using CPPUnit instead of Google Unit (gunit). Any ideas why?


I guess Google is in favour of spaces over tabs by the look of that



Ugh that's it, I never cared before, but now I'm switching to DuckDuckGo.


Bing for me: they open brace on the same line as a control statement/function declaration.

Allman style forever! [1]

1. https://en.m.wikipedia.org/wiki/Indentation_style#Allman


Please for god's sake, let this language die. There has been nothing this bad in the entire history of programming languages and now Google wants to impose more undefined behaviors on our professional lives. Anyone starting out with learning should go through https://www.rust-lang.org path and anyone who's wise enough to understand pros and cons of such language will automatically choose rustlang over them in 2018.

Even in comparison with C, it falls short. C was a beautifully designed language.

The features of the C language were added with purpose. They were intended to solve a real problem and solve that problem they did. Simple arithmetic with promotion. Automatic register allocation with a portable (between compilers) ABI. A simple-but-handy preprocessor. And so on. C is also a lean language: a single person can feasibly write a C compiler in a relatively short time (tinycc is a C99-compliant C compiler written in just 65kLOC of C!). C set out to achieve a clear goal and it achieved its goal. Thanks to the cleanness of C lots of quality compilers came on the market quickly and even decent OSS solutions were available early on.

In contrast, C++ never had a clear goal. The features of C++ were added almost at random. Stroustrup's original idea was essentially "C is cool and OOP is cool so let's bolt OOP onto C". Retrospectively, OOP was massively overhyped and is the wrong tool for the job for most of the people most of the time. Half of the GoF design patterns just emulate idioms from functional programming. Real OOP languages like Smalltalk and IO express many useful things that C++ cannot. The feature that C needed most was perhaps parametric polymorphism (aka generics in Java and C#, first seen in ML in the late 1970s) but instead of that C++ got templates that weren't designed to solve any particular problem but rather to kind of solve several completely unrelated problems (e.g. generics and metaprogramming). Someone actually discovered by accident that C++ templates are Turing complete and they wrote and published a program that computed prime numbers at compile time. Wow. A remarkable observation that led to decades of template abuse where people used templates to solve problems much better solved by other pre-existing solutions such Lisp macros and ML polymorphism. Worse, this abuse led to even more language features being piled on top, like template partial specialization.

The massive incidental complexity in C++ made it almost impossible to write a working compiler. For example, it remains extremely difficult to write a parser for the C++ language. The syntax also has horrible aspects like List<Set<int>> being interpreted as logical shift right. None of the original C++ compilers were reliable. During my PhD in 2000-2004 I was still stumbling upon dozens of bugs in C++ compilers from GNU, Intel and SGI. Only after two decades did we start to see solid C++ compilers (by which time C++ was in decline in industry due to Java and C#).

C++ is said to be fast but the reality is that C++ is essentially only fast when you write C-like code and even then it is only fast for certain kinds of programs. Due to the "you don't pay for what you don't use" attitude, C++ is generally inefficient. RAII injects lots of unnecessary function calls at the end of scope, sometimes even expensive virtual calls. These calls often require data that would otherwise be dead so the data are kept alive, increasing register pressure and spilling and decreasing performance. The C++ exception mechanism is very inefficient (~6x slower than OCaml) because it unwinds the stack frame by frame calling destructors rather than long jumping. Allocation with new and delete is slow compared to a modern garbage collector so people are encouraged to use STL collections but these pre-allocate huge blocks of memory in comparison so you've lost the memory-efficiency of C and then you are advised to write your own STL allocator which is no better than using C in the first place. One of the main long-standing advantages of C over modern languages is the unpredictable latency incurred by garbage collectors. C++ offers the worst of both worlds by not having a garbage collector (making it impossible to leverage useful concepts like purely functional data structures properly) but it encourages all destructors to avalanche so you get unbounded pause times (worse than any production GC). Although templates are abused for metaprogramming they are very poor at it and C++ has no real support for metaprogramming. For example, you cannot write an efficient portable regular expression library in C++ because there is no way to do run-time code generation and compilation as you can in Java, C# and languages dating back to Lisp (1960). So while Java and C# have had regular expressions in their standard libraries for well over 10 years, C++ only just got them and they are slow.

C++ is so complicated that even world experts make rookie mistakes with it. Herb Sutter works for Microsoft and sits on the C++ standards committee where he influences the future of C++. In a lecture he gave his favorite 10-line C++ program, a thread-safe object cache. Someone pointed out that it leaks memory.

My personal feeling is that the new Rust programming language is what C++ should have been. It has useful known features like generics, discriminated unions and pattern matching and useful new features like memory safety without garbage collection.


There is nothing beautiful about C other that having had the luck UNIX was available for free and thus adopted by startups like Sun and SGI.

"Oh, it was quite a while ago. I kind of stopped when C came out. That was a big blow. We were making so much good progress on optimizations and transformations. We were getting rid of just one nice problem after another. When C came out, at one of the SIGPLAN compiler conferences, there was a debate between Steve Johnson from Bell Labs, who was supporting C, and one of our people, Bill Harrison, who was working on a project that I had at that time supporting automatic optimization...The nubbin of the debate was Steve's defense of not having to build optimizers anymore because the programmer would take care of it. That it was really a programmer's issue....

Seibel: Do you think C is a reasonable language if they had restricted its use to operating-system kernels?

Allen: Oh, yeah. That would have been fine. And, in fact, you need to have something like that, something where experts can really fine-tune without big bottlenecks because those are key problems to solve. By 1960, we had a long list of amazing languages: Lisp, APL, Fortran, COBOL, Algol 60. These are higher-level than C. We have seriously regressed, since C developed. C has destroyed our ability to advance the state of the art in automatic optimization, automatic parallelization, automatic mapping of a high-level language to the machine. This is one of the reasons compilers are ... basically not taught much anymore in the colleges and universities."

Fran Allen interview, Excerpted from: Peter Seibel. Coders at Work: Reflections on the Craft of Programming

C++ has a clear goal, as Bjarne puts so eloquently, never having to write C again.


Donald Knuth likes it: "I think C has a lot of features that are very important. The way C handles pointers, for example, was a brilliant innovation; it solved a lot of problems that we had before in data structuring and made the programs look good afterwards. C isn't the perfect language, no language is, but I think it has a lot of virtues, and you can avoid the parts you don't like." http://tex.loria.fr/litte/knuth-interview [1993]

Counterpoints:

Of course, you can only avoid the parts you don't like if you're a lone academic working on a new program by yourself from scratch with no third party integration or legacy code.

Knuth's own languages generally make the eyes bleed.

There is no accounting for taste.


>Half of the GoF design patterns just emulate idioms from functional programming. Real OOP languages like Smalltalk and IO express many useful things that C++ cannot.

>Although templates are abused for metaprogramming they are very poor at it and C++ has no real support for metaprogramming.

>because there is no way to do run-time code generation and compilation

It seems that the language you want is not Rust but Common Lisp, which will give you plenty of metaprogramming, easy run-time code generation, (optional) functional programming, and optional object-oriented programming with an OOP system even more powerful than Smalltalk's OOP system.

>My personal feeling is that the new Rust programming language is what C++ should have been.

Well, Free Pascal is already, currently, everything that C++ should have been. No need to go into Rust.


I just want to let you know I enjoyed this rant. It's a shame hacker news has this downovting/upvoting nonsense. Popular opinions can be worth sharing.


Chapter 1: Use Golang


Chapter 32: Please (GC pauses the world) rewrite (GC pauses the world) it (GC pauses the world) with (GC pauses the world) C++.


Please don't do this here.


I used to touch some cc files at Google. I must say they are really horrible. Basically everything relies on bizarre internal frameworks glued together with opaque macros. Some of the least legible c++ code bases I've worked on.


I've written a lot of C++ at Google. Macros are used sparingly, e.g. for command line flags:

https://gflags.github.io/gflags/

They are discouraged for use in place of an API:

https://google.github.io/styleguide/cppguide.html#Preprocess...


This sounds really off, and much different than my experience. Honestly, if there's a place in the world that produces quality C++, it's google.


Do you have any insights as to how those internal frameworks developed?

One would think that with the ease and ubiquity of options these days, the homegrown framework (that is often proprietary to the company D-:) over open standards would be disappearing, but I still encounter it often, even in newer products.


The commenter is welcome to his opinion but I think it's pretty wrong. Google has a few internal frameworks for things but mostly they evolved before the standard library had reasonable standardized equivalents and in cases where the standard has grown to encompass these things there's been orderly migration towards using the standard equivalent where it makes sense. It's a quite well maintained codebase with good sensible standards and review process as well as teams of people whose sole job it is to go through to analyze and migrate whole swathes of the code base for improvement.

Plus alot of Google's internal stuff is being open sourced: https://opensource.googleblog.com/2017/09/introducing-abseil...

You can waltz through that code as well as other open sourced things and judge for yourself on the quality.




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

Search: