336 points · by ChuckMcM · 6y ago · 253 comments
Any suggestions? Pointers to repos would be appreciated. Thanks!
https://github.com/hanickadot/compile-time-regular-expressio...
https://github.com/nlohmann/json
If you've not written C++ code before, it can take a while to catch up with the latest developments in C++23. Start with C, and learn these, in approximately the specified order:
1. lvalue references.
2. Constructors, destructors, and inheritance.
3. Annotations such as const and noexcept on members.
4. Simple type templates, and value templates.
5. constexpr, std::move, and rvalue references.
6. Type traits and std::enable_if.
7. Concepts.
Once you learn the core language features, learning the various data structures/algorithms in `std` should just be a matter of looking them up in cppreference, and using them over and over again.
Good luck.
That said, I like your ordering too.
The other confounding factor is that I have also written a lot of Java code (both during the development of the language and afterward for my column in Javaworld) which I really enjoyed, but it too "fixes" some things which James disliked about C++ (and as a long time C programmer I understood quite well).
As a learning experience, this journey has been confounding, enlightening, and painful in equal measures :-)
If you find yourself reaching for std::shared_ptr and virtual functions more often than once in a blue moon, you are suffering from Java Disease, and are writing bad code.
Anything that seems to be something Java "fixed" is a thing they failed to understand. You will have to unlearn those, along with myriad bad C habits, many of which you don't know you have. It takes sharp observation to catch them.
As someone with north of 15 programming languages that I consider myself "fluent" in, albeit some latency involved in ones I've not used for a while, I always look for the idiomatic expression of computation. It is the difference between "writing FORTRAN in <x>, and writing an algorithm in <x>."
One of main the reasons I posted the question is that I found that design patterns I expected to be there, were not there, or were not idiomatic, and for whatever reason I am reasonably good at figuring out when something is "not quite right."
That said, I think it is unfair to characterize the choices of any language designer as either ignorant or wrong. As someone who participated in the design of Java I can assure you that the team "understood" why C++ did what it did. During that development, if there was any confusion, Guy Steele, whose office was three down from mine, would eloquently explain it so that everyone could understand it. That is not to say there weren't different opinions about "better" ways and "worse" ways to do things, Bill Joy was never a big fan of the Java choices and often took the opposing view across from Gosling. The language that Bill was designing was called 'Self' and it embodied his design choices, just as Java embodied Jame's design choices.
Me, as a systems guy, could really care less if Boolean was a first class type or just a uint1. I just want to write code that works.
constexpr seems to try and step in, but there still is a large codebase around which is hard to maintain and extend. IMHO D and zig show that it can be better to have compile- and runtime-syntax much closer together.
Some of the older glog code is pretty nice with regards to a very vanilla and portable treatment of macros https://github.com/google/glog/tree/master/src/glog
While I wouldn't necessarily recommend Boost as a model project / repo ( https://github.com/boostorg ), it's worth checking out to help understand why modern decisions were made the way they were.
> Why did Kenton do this? He can speak for himself,
An incomplete list of reasons:
1) At the time I started the project, a lot of things that KJ replaces, like std::optional, didn't actually exist in the C++ standard yet.
2) A lot of the stuff in the standard library is just badly designed. Take std::optional, for instance. You'd think that the whole point of using std::optional instead of a pointer would be to force you to check for null. Unfortunately, std::optional implements operator* and operator-> which are UB if the optional is null -- that's even worse than the situation with pointers, where at least a null pointer dereference will reliably crash. KJ's Maybe is designed to force you to use the KJ_IF_MAYBE() macro to unwrap it, which forces you to think about the null case.
3) A lot of older stuff in the C++ standard library hasn't aged well with the introduction of C++11, or was just awful in the first place (iostream). C++11 really changed the language, and KJ was designed entirely with those changes in mind.
4) The KJ style guide (https://github.com/capnproto/capnproto/blob/master/style-gui...) adopts some particular rules around the use of const to help enforce thread safety, the specific philosophy around exceptions, and some other things, which differ from the C++ standard library's design philosophies. KJ's rules have worked out pretty well in my experience, but they break down when building on an underlying toolkit that doesn't follow them.
5) This is a silly matter of taste, but I just can't stand the fact that type names are indistinguishable from variable names in C++ standard style.
6) Because it was fun.
Do these reasons add up to a good argument for reinventing the wheel? I dunno. I think it has worked well for me but smart people can certainly disagree.
Dereferencing null optionals is UB for consistency with dereferencing pointers. All uses of operator* should have the same semantics and the C++ standards committee did the right thing by ensuring that with optionals. Checking for null in operator* would break consistency.
If you want to dereference an optional that may be null, use the .value_or() method. For the times when you absolutely know the optional has a value use operator*.
If you’re wondering why you would use an optional over a pointer. The idea is that optionals allow you to pass optional data by value. Previously if you wanted to pass optional data, you’d have to do it by reference with a pointer. This is part of c++’s push towards a value-based style, which is more amenable to optimization and more efficient in general for small structs (avoiding the heap, direct access of data). Move semantics are a part of that same push.
Yes, and kj::Maybe was doing the same before std::optional was standardized.
It's disappointing that the committee chose only to solve this problem while not also solving the problem of forgetting to check for null -- often called "the billion-dollar mistake".
> Dereferencing null optionals is UB for consistency with dereferencing pointers. All uses of operator* should have the same semantics
My argument is that `std::optional` should not have an operator* at all. `kj::Maybe` does not have operator* nor `operator->`.
> If you want to dereference an optional that may be null, use the .value_or() method. For the times when you absolutely know the optional has a value use operator*.
This is putting a lot of cognitive load on the developer. They must remember which of their variables are optionals, in order to remember whether they need to check for nullness. The fact that they use the same syntax to dereference makes it very easy to get wrong. This is especilaly true in modern IDEs where developers may be relying on auto-complete. If I don't remember the type of `foo`, I'm likely to write `foo->` and look at the list of auto-complete options, then choose one, without ever realizing that `foo` is an optional that needs to be checked for null.
In KJ, you MUST write:
KJ_IF_MAYBE(value, maybeValue) {
use(value);
} else {
handleNull();
}
Or if you're really sure the maybe is non-null, you can write: use(KJ_ASSERT_NONNULL(maybeValue));
This does a runtime check and throws an exception if the value is null. But more importantly, it makes it really clear to both the writer and the reader that as assumption is being made.The point of optional is to avoid being consistent with the bad parts of pointers. And making it undefined rather than a guaranteed crash is even crazier.
Ford doesn't sell cars that burst into flames for consistency with the Pinto.
In practice I believe that all standard libraries have a lightweight check mode that can assert even in release mode.
I still think if you wanted to re-write a capnp library today, you'd still need kj, or at least most of it, simply for the memory control. The added benefit of kj is that you don't have to deal with C++ STL bugs and quirks. E.g. I believe C++ spec didn't require std::optional to use in-place new until recently ...
Also curious if you have any comments on this read of kj from a software management perspective. I imagine trying to sell the investment of writing something like kj at a company and it being a tough sell, even if capnp was approved. You clearly knew what you were doing from the outset and certainly nobody could have done it better. But I believe capnp sits close to the decision boundary of where many companies decide to invest in greatness or not, and reflection might shed light on why some managers make the wrong choice on something like this.
In 2013, the C++ standard library was sorely missing a string representation that allowed pointing into an existing buffer, which was important for Cap'n Proto to claim zero-copy. C++17 introduced std::string_view, which would fit the bill, but that wasn't there in 2013, so I wrote my own StringPtr. I added Maybe because I needed it all over the place (and std::optional didn't exist), and then for RPC I needed to create the Promise framework (std::future and such didn't exist yet). At that point I looked at these things and said "these are generally useful outside of Cap'n Proto, I should turn them into a library", and that's how KJ got started.
> I imagine trying to sell the investment of writing something like kj at a company and it being a tough sell
Well, many companies have things "like KJ". Google has Abseil, Facebook has Folly. But just like KJ, these things didn't start with someone saying "Hey I want to make a new C++ toolkit", they started with people writing utility code that they needed for other things, and then splitting that code out to make it reusable. Eventually the utilities accumulate into their own ecosystem. I generally don't add anything to KJ unless I explicitly need it for something else I'm working on. I actually would argue that it would be a bad business decision to spin up a project to create something like KJ or Abseil or Folly from scratch; such projects are likely to spend too much time solving the wrong problems. The best toolkits and platforms come from projects that were really trying to build something on top of that platform, and let their own real-world problems drive the design.
That said, arguably, Cap'n Proto itself is a bit of a counterpoint. I started Cap'n Proto after quitting Google. I did not have any real business purpose, I just wanted to play around with zero-copy, which I'd thought about a lot while working on Protobuf. That said, I did have the previous experience of maintaining Protobuf at Google for several years, which meant I already had a pretty good idea of what the real-world problems looked like, and I stuck pretty closely to Protobuf's design decisions in most ways. And then starting in 2014, I started working on Sandstorm, build on top of Cap'n Proto, and further development was driven by needs there. (And since 2017, Cloudflare Workers has been the main driver.)
I am not sure if the time I spent starting Cap'n Proto in 2013 would have made sense from a business perspective. If I'd wanted to start Sandstorm immediately, building on Protobuf would probably have been the right answer.
I would say that low-level developer tooling in general is pretty tough to make a business out of, because everyone expects it to be free and open source. It's also pretty tough to build as part of another business, because usually creating something new from scratch doesn't justify the cost, vs. using something off the shelf. I feel like the only people who can create new fundamental tools from scratch (especially things like programming languages) are giant companies like Google, and random hackers who are lucky enough to be able to mess around without funding.
Sorry, that probably isn't the answer you were looking for. I don't like it either. :/
Interestingly, though, at the time I wrote the guide, Rust was in its infancy, and I didn't know anything about it. :)
> Value types always have move constructors (and sometimes copy constructors). Resource types are not movable; if ownership transfer is needed, the resource must be allocated on the heap.
In Rust, all types (including resources) are movable.
> Value types almost always have implicit destructors. Resource types may have an explicit destructor.
What's an explicit destructor? Rust's File type closes upon destruction, and one criticism of the design is that it ignores all errors. The only way to know what errors occurred is to call sync_all() beforehand.
However, "Ownership" and "Reference Counting" (and "Exceptions" to an extent) feel very Rust-like.
> If a class's copy constructor would require memory allocation, consider providing a clone() method instead and deleting the copy constructor. Allocation in implicit copies is a common source of death-by-1000-cuts performance problems. kj::String, for example, is movable but not copyable.
When you include such a class in a larger structure, it breaks the ability for the outer class to derive a copy constructor automatically (even an explicit one, or a private one used by a clone() method). What's the best way to approach this?
The upshot is that “professional grade” C++ is often impenetrable (I tried to understand the implementation of boost::intrusive_list once. Yikes.)
LLVM is often cited as a very clean codebase and I think that holds up. Facebook’s folly is another good one (although it occasionally dives into template metaprogramming madness).
Hopefully I’ll be forgiven for also plugging a few projects I used to work on, that might hit a sweet spot between utility and code complexity: - Glow, a compiler for neural networks: https://github.com/pytorch/glow - ReDex, a bytecode optimizer for Android: https://github.com/facebook/redex
There was a nice blog post a few years back called “c++11 is a scripting language” that is unfortunately offline now; it did some task like reading lines from a file and sorting them, and it wasn’t dramatically more complicated than the same thing in Python. It’s worth doing a few of those kinds of exercises to get a feeling for the language.
To be fair library code, especially library code that's supposed to run on a huge number of compilers and platforms, must include support for a ton of weirdo special cases which ultimately render it unreadable to someone not steeped in it. It also has to handle weird corner cases most developers might not think of, either because it's just a weird corner of the standard or because it might commonly be, say, embedded in some other structure or used in an unusual template expansion which would imply non-obvious constraints. This BTW is true of any language.
By contrast: I wrote a small lock-protected container template used in a local code base. It's short, fast and easy to use. Also easy to understand if you bother to read the code (but it's so easy to use, why bother). But there's a huge tradeoff: it doesn't act completely like a regular container; it only handles cases we care about in our code base and only works on the three compilers we care about. There is zero interest in implementing a more general solution. When this object doesn't work, sometimes we extend it and sometimes we change the caller.
So which would be a better example to read? I'd argue: neither.
[1]: https://twitter.com/github/status/1017094930991370240
Also on HN: https://news.ycombinator.com/item?id=17897283
PS: A fork of 2048.cpp was even used as a demo at CppCon 2020 (https://www.youtube.com/watch?v=HrOEyJVU5As)
A couple of years ago I wrote a text-editor to have a realistic example of what I consider a nice modern architecture using immutable data-structures. In the README there is also a link to a talk where I cover some of the design and structure:
https://github.com/arximboldi/ewig
Libraries that it uses:
https://github.com/TTimo/doom3.gpl
I find it to be extremely readable, and it has a C with classes approach that I tend to gravitate towards when I'm developing in C++. It is not an example of "modern C++".
Modern C++ and it's use of std::unique_ptr / std::move is so much nicer vs. manual memory allocation.
Function is 200 lines long, with 8 or so levels of nesting. Also "goto breakout"
To address the objections below, the function reads from a file into a pixel buffer. It's not some tricky in-place update. That's a great candidate for a more functional style.
Here's more ick:
https://github.com/TTimo/doom3.gpl/blob/aaa855815ab484d5bd09...
Surely that could be factored better.
Down-voters go read Carmack's own article:
https://gamasutra.com/view/news/169296/Indepth_Functional_pr...
I think it's funny that people disagree here. This is exactly the stuff a modern linter would flag in an automated code review.
Sure enough, here's a linter. I think this is essentially the same codebase:
https://lgtm.com/projects/g/Edgarins29/Doom3/context:cpp
"Code quality: D" (on an A-F scale)
And by the way, I have the utmost respect for Carmack. I just wouldn't hold up this codebase as great.
The code is readable and self documenting. The file format is practically documented by reading this code. The function has a single obvious purpose.
The function length and nesting is more a result of the file format itself. Seems like a waste of time breaking this function up. It would serve no other purpose than delaying the ship date and making this function less readable, a function that may likely never need to be visited again.
Moreover, here's approximately how I'd write that TGA loading function:
1. Write a function to load just a header. 2. Unit test the function with a header. 3. Write a function to do the RLE decoding. 4. Unit test the function with some data. 5. etc. 6. Start assembling the pieces. 7. Unit test the whole thing.
Meanwhile, you tried to write it all in one monolithic function, and so now you're testing the whole thing (hopefully with a unit test) and you're staring at the debugger (or worse, some printf output) wondering what little mistake you made. Maybe if you're brilliant, like Carmack, you beat me to the finish line. But most of us are mere mortals.
Simple code is easy to write, maintain, and optimize later. Despite the code looking messy, I find it easy to understand and navigate.
A counter example of truly confusing code, which kind of does similar things, would be something like this: https://github.com/ImageMagick/dcraw/blob/master/dcraw.c
Anyway, he's just wrong about long functions being a-ok. I suspect he doesn't write many unit tests. This is the main benefit of separating the code into smaller functions. You can test each. Even if it's just parsing an image file header.
That some of the folks here think smaller functions are useless because they would only be called from from one function just shows they don't write enough tests.
> Besides awareness of the actual code being executed, inlining functions also has the benefit of not making it possible to call the function from other places. That sounds ridiculous, but there is a point to it. As a codebase grows over years of use, there will be lots of opportunities to take a shortcut and just call a function that does only the work you think needs to be done. There might be a FullUpdate() function that calls PartialUpdateA(), and PartialUpdateB(), but in some particular case you may realize (or think) that you only need to do PartialUpdateB(), and you are being efficient by avoiding the other work. Lots and lots of bugs stem from this. Most bugs are a result of the execution state not being exactly what you think it is.
in general I don't think it's worthwhile to split a long function into several static helpers just to get under an arbitrary maximum function length target. I don't think it leads to a net improvement in readability, since I now have to go back and forth between the helpers and the main function to see in what order the helpers get called (what if someone swaps the order of helperA and helperB but not the order of their definitions?). imo this is only worth doing if you're also willing to think long and hard about what happens if someone uses your helpers in a different context.
Could they have abstracted MakeMegaTexture_f into something that built up leaves of tga structs they interweave in that function? Or just chunk through them with the tga data structure. Our standards for what is good code has changed with our understanding of code.
Can you rewrite it in a way that's readable, performant and understandable/maintainable to someone with an understanding of the knowledge domain?
I agree, the code is ugly. I disagree it would be better if converted to some OOP hierarchy, it would be probably less understandable even if the code was tidier
Code like
SnarfleBlaster = new SnarfleBlaster();
SnuggleNerfer = new SnuggleNerfer();
Guffles guffles = SnarfleBlaster->Blast();
SnuggleNerfer->Tumbles(guffles);
Is tidy but absolutely denseAnd for that matter, even the same person might write in different styles depending on the situation. And the same exact style might be terrible for one situation but awesome for another.
With all that said, one "good" kind of codebase to at least know (even if you can't emulate it) is the kind of codebase that is modeled after the C++ standard library. Some Boost libraries (not all!) are great examples of this. Probably the best example I can think of off the top of my head is Boost.Container:
https://www.boost.org/doc/libs/1_74_0/boost/container/vector...
Note that this does not mean you should write code like this for your applications, though. Boost is heavyweight with the templates/headers/macros and these classes are meant to be extremely generic. Your application-level code does not necessarily need to meet the same types of constraints, and it's just not worth the effort in most cases (as well as being slower to compile). But if you can write this kind of code when it's warranted, it ends up being very high-quality. (Some parts of this involve a lot of difficult work, like paying attention to exception-safety, that is often unnecessary. Other parts are quite simple and well worth picking up, e.g. liberal use of typedefs. And everything else in between.)
A more typical example of a codebase might be some of wxWidgets, e.g.:
https://github.com/wxWidgets/wxWidgets/blob/v3.1.4/src/gener...
It's not in the style of the standard library (so you won't find it to be as generic, exception-safe, etc.) but it's pretty decent.
It's not just that it has a huge and growing feature-set, it also has an outsize wealth of dark corners. As a slight silver lining, there's an excellent community on StackOverflow where these quirks are explained well.
You can spend hours just reading about initialization in C++. I have, and I can only recall a small fraction of it (but I rarely use C++). It's nightmarish in ways you'd never imagine. [0][1][2]
[0] https://stackoverflow.com/a/54350350/
> https://www.boost.org/doc/libs/1_74_0/boost/container/vector...
Which I find absolutely hilarious. Thousands of lines of boilerplate for something as simple as an dynamically resizable array. Only for the _header_ which has to be included at each location that uses a vector either directly or indirectly. These are the kinds of things that prevent me from touching C++.
Boost.container::vector implements the full standard vector interface (that's already a large interface), plus quite a few non-standard extensions (significantly it has built-in support for default initialization).
Boost.container also has support for stateful allocators and custom pointer types so that it can be used, for example, on shared memory (in fact boost container was originally a sub-library of boost.interprocess). That alone will increase the complexity significantly.
It also I believe still support pre-c++11 (and substandard post c++11) compilers, so there is a lot of compiler workarounds and emulation of c++11 features.
Also, being a template, the whole implementation is just in the _header_.
As for being a template, that doesn't preclude from having most of the implementation in a .cpp file. In fact that's highly desirable (separate compilation).
Please don't let boost stop you.
At my team we avoid boost like the plague and prefer terse and pragmatic code. IMO C++ is best approached like C but with convenient data structures in the standard library - and tons of patterns that _may_ be taken into use if they simplify the code.
That said, unless you are working in a specific setting where C++ is obviously the best tool, you probably should not use C++. Even at best of times C++ is complex and unproductive. But it offers an unbeatable combination of ecosystem maturity, robustness, close to the metal performance and high level concepts to fit few slots better than anything else.
I frequently sit down and write 2000 lines of C++ code, and when it compiles, it works. Aim for that.
I've been using C++ as a daily workhorse since the early 90s and Boost and its standardized derivatives is easily the worst thing that ever happened to the language. It may all make logical sense, but the end result looks, basically, like butt. It is not a refined, thoughtfully evolved language that is a pleasure to use. It has so many features bolted on at so many different angles that it has no distinct shape anymore. Design by committee at its finest.
honest question, why do you think liberal use of typedefs is a good habit to pick up?
That said, I'm not suggesting you use them indiscriminately. 'this_type' and 'value_type' are often useful; 'difference_type' and 'size_type' generally won't gain you anything...
• https://www.scylladb.com/2020/03/26/avi-kivity-at-core-c-201... • https://www.scylladb.com/2020/05/05/how-io_uring-and-ebpf-wi...
https://github.com/mmp/pbrt-v3
That said, IMHO, there is no "clean" C++ code. There are C++ codebases that use different styles, and their "quality" more or less is context sensitive.
Personally I felt the best tutorial to C++ were actually two other programming languages - Scheme and F#.
Scheme drove in the concept that it's totally fine to model things based on the shape of the data and that you don't need to create type based abstractions around every thing.
F# then demonstrated how a language with type system is supposed to work.
The problem with C++ is that the language is so verbose that unless you have an abbreviated model in your head how a type based language can be used to solve problems in best way, you will get lost in trivial C++ minutiae.
So, personally, I generally think "Am I solving a Scheme like problem or Standard ML like problem" and then try to apply C++ as simply as possible.
Several academics have created a career of how to patch C++/Java/C# with concepts that make them less fragile in a collaborative context:
https://en.wikipedia.org/wiki/Design_Patterns
https://www.amazon.com/Design-Patterns-Elements-Reusable-Obj...
In my opinion design patterns are not a fundamental concept, but rather provide common syntax for collaboration purposes for various patterns that are parts of language and more or less invisible in e.g. Scheme or F#. But if one is diving into C++ it's probably convenient to be familiar with these concepts.
If your C++ code is "so verbose", you are Doing It Wrong, most likely by doing it the old way. C++98 was verbose.
So - verbose in terms of the spec which describes what the code actually does and mental chatter I have to do with myself when writing it "should I return a ref or a smart_ptr or a value or should I use move semantics..." whereas in F# it's just a ref and garbage collector will deal with it. So I can skip the mental chatter part.
a) displays a way to put together a non-trivial C++ application
b) displays several extremely useful graphics related algorithms and patterns
c) Is documented on a level and quality few public equal code bases reach - so get the book first and then start reading the sources
Interesting - can you talk a little bit about why those specific design choices are questionable from a modern C++ POV? How would you do it differently, given the problem & domain PBRT covers?
I ask because my mental "sweet spot" in terms of understanding and writing C++ is approximately C++11. It's pretty easy for me to go into symbol shock when I see some of the latest stuff in C++17 and C++20... and I suspect I'm not the only person that happens to.
A much better approach is to allocate large chunks of memory at one time and run through the arrays of floats directly. Instead of tracing and shading one path ray all the way through, finding out where it hits, running the brdf, looking up textures, casting another ray, etc. it is much better to do each stage in large chunks.
Going from data structures holding lots of virtual pointers to something like I described above can be a substantial improvement in speed and give a lot of clarity at the same time.
Many times programs with a lot of inheritance end up with their execution dictated by types calling other types' functions, which makes it more implicit and buried rather than linear in a top level function. It becomes similar in a way to callback hell where you are trying to track down how the program gets to a certain place. Many times it takes adding break points and walking back through the call stack to reverse engineer it, rather than looking at a single top level function that has a lot of steps.
Easy tasks:
- Challenge yourself by cloning projects reading their README and compiling/running them [1]
- Port projects to other platforms (e.g. Windows-only game examples to Linux/Mac/FreeBSD) [2]
Codebases I've studied [3]:
sdl/graphic widgets: openttd, aseprite, nanogui(-sdl)
runtime / abstraction: v8, node, protobuf, skia
templates / language integration: pybind11, boost-python
wrapping C: libsdl2pp (SDL2 wrapper)
small: tmux-mem-cpu-load, uMario_Jakowski
huge: blender
Architecture / theory: https://aosabook.org/en/wesnoth.html, https://aosabook.org/en/audacity.html, https://aosabook.org/en/cmake.html, https://www.aosabook.org/en/llvm.html
Books: Scott Meyers C++ books
[1] It's C, but to push myself to grok build systems I tried to port tmux's autotools build system to CMake: https://github.com/tony/tmux/compare/master...tony:cmake
[2] https://github.com/jakowskidev/uMario_Jakowski/pull/1
[3] https://github.com/tony/.dot-config/blob/5c59f46/.vcspull.ya...
But I would hardly call the build system the main blocker unless the software module under development is near trivial in complexity.
In my opinion, the very best C++ is plain-old-C that uses modern C++ standard libraries, while carefully controlling the definition of the memory allocator for those libraries.
Your idea of heavenly C++ sounds like my idea of hell.
I'm concerned this may be the definitive C++ experience...
Not to start a debate but just genuinely curious...
Do you avoid writing ~destructors() in C++ to adhere to "plain C" principles?
Imo, destructors (RAII) is one of the killer C++ features. There's a lot of buggy plain C code that has a malloc() but missing the associated free() and/or an openXyz() but missing the closeXyz(). Plain C has to manually write cleanup() functions or code generators to simulate dtors() which is a hassle.
I guess the related larger question is if the "best C++" means avoid writing any classes at all? (E.g. Linux source with plain C uses structs and function parameters to simulate OOP: https://lwn.net/Articles/444910/)
{
something a_thing {};
...;
}
Is a perfectly reasonable way to allocate something on the stack and have it unwound at the end of the block. No pointers needed. Perhaps I'm misunderstanding your argument.`new`, much less `malloc` hardly ever need appear. I'm working in a reasonably large code base that has four uses of new: three hidden in in internal graph node construction and one in a high-performance deserializer (actually that last is in the process of being replaced by code that simply requests pages from the OS). There are very few cases where user code might allocate memory with `new` these days.
pooya13's argument stands as well.
The worst way is to emulate Java, putting everything in derived classes with virtual functions, and trafficking in shared_ptr. We call that Java Disease.
Using C++ as a "better C" leaves almost all the potential benefit on the table, leaving you hardly more productive than you were in C. Coding C++ as C++, you can be worlds more productive, making the compiler do most of your work for you, and leaving the bugs behind in the code you didn't need to write.
- http://www.serenityos.org/ (Andreas Kling)
- https://godotengine.org/ (Juan Linietsky)
Those are among my favorites because of simplicity and readability vs the complexity of the domain they implement.
In addition to those I highly recommend studying ClickHouse’s codebase. There are brilliant design and engineering bits everywhere. I learned more from studying this codebase than most other I can think of, especially with regards to templates meta-programming ( I learned about “template template parameters” from coming across extensive use of those there ). It’s actually somewhat challenging to grok what’s going on — but it is worth pushing through until you “get it”.
To generalize:
- Google software like protobufs and chrome are good examples of accepted C++ practice in the general software industry. It goes a bit overboard in the C++-iness for my taste, but that's just a personal thing.
- For game engines, Unreal Engine 4 is good example of pretty well-organized large C++ codebase. For size and complexity of the beast, it is not hard to read the code. Understanding the overall structure depends on how deep you are already into games.
- There are some games over the years that have released their source code. I consider Monolith's games (F.E.A.R, No One Lives Forever 2) to be pretty well-organized C++ code. They're very out of date now, but you can apply newer C++ features to their basic structure and still come away with decent code.
To learn C++, I would start with your own C code and the morph it in the following ways:
- Use C++ objects to represent functionality boundaries and data abstractions. You probably have a bunch of structs and functions that operate on them. Convert those to C++.
- Start using destructors to automatically clean up objects. Read up on RAII patterns.
- Use smart pointers instead of dynamically allocating/freeing memory with malloc/new/free/delete.
After these basics, you can branch out into exploring more in depth with templates, fancy C++17/20 features etc. Don't try to use all the features and capabilities at the outset. You can end up with a codebase you won't want to read in a year, let alone other people on your project. I've seen massive, unreadable templated code because someone got a shiny new template hammer and banged away at every problem as a nail.
I would also recommend using an IDE with decent tooling. C++ is insanely hard to parse. If you go so template/macro crazy that you confuse your IDE context parser, you will most certainly confuse other people reading your code.
* To study OO expression of C++ via Class libraries/Frameworks i recommend a study of "Microsoft Foundation Classes (MFC) library" paired with the book MFC Internals. The code is available with the installation of Visual Studio.
* P.J.Plauger's The Standard C Library and The C++ Standard Template Library(with Alexander Stepanov, Meng Lee and David Musser) will teach you excellent C and C++ Generic programming skills. Code available with the standard C++ toolchain installation.
* The Boost libraries paired with the book C++ Template Metaprogramming: Concepts, Tools, and Techniques from Boost and Beyond.
* The FXT library of Algorithms by Jorg Arndt (https://www.jjj.de/fxt/fxtpage.html) along with its book Matters Computational for writing optimized C++ code.
I would also suggest reading the following two classics to learn designing in C++;
* Multi-Paradigm Design for C++ by James Coplien.
* Scientific and Engineering C++: An Introduction with Advanced Techniques and Examples by Barton and Nackman.
Mesos is interesting as a whole but it also has some parts that are notoriously hard to get right (like their Paxos implementation).
It also contains an RPC library that implements an actor model and uses futures and promises (https://github.com/apache/mesos/tree/master/3rdparty/libproc...), as well as a header-only utility library called Stout (https://github.com/apache/mesos/tree/master/3rdparty/stout) with a lot of useful functions.
https://github.com/abseil/abseil-cpp/blob/master/absl/string...
LevelDB is good reading, too.
some code for study are listed here: https://github.com/rigtorp/awesome-modern-cpp
Modern C++ looks very, very different from C, and even more different from Java. So, if you see code that looks like one of those, you know it is not a thing to emulate.
Certain companies, notably Mozilla and Google, have extremely peculiar coding standards that badly warp how code has to be written for them. You do not want to emulate that code. If you see classes with "Init" and "Deinit" members, and constructors that don't do anything, you know you are in a dark back alley headed for a world of suffering.
If you see code that looks like it might as well be C, it's probably bad code. Modern C++ is a very, very different language from C. Most of your C habits, if you have any, are bad C++ habits that you will need to work hard to unlearn. In particular, if you handle naked pointers much, you are Doing It Wrong.
If you see code organized like Java, full of shared_ptr and virtual functions, it's certainly bad code. (I think Dropbox just published a big library that was virtual functions from top to bottom. Shiver.) We call that Java Disease. Inheritance and virtual functions are occasionally useful, as pure mechanism, but not as an organizing principle.
Modern C++ code works with values more than pointers or references, and prefers to pass objects by move over by reference. If you actually see allocations, and particularly deallocations, in top-level code, it is very likely to be bad code.
- Abseil: https://github.com/abseil/abseil-cpp https://cs.opensource.google/abseil
- Tensorflow: https://github.com/tensorflow/tensorflow/tree/master/tensorf... https://cs.opensource.google/tensorflow
- Chrome https://chromium.googlesource.com/chromium/src.git/+/refs/he... https://source.chromium.org/chromium
There is a very high bar for C++ code quality at Google, and also a published style / best practices guide as well as a code search engine to browse the code more easily.
Google's allergy to exceptions pollutes their designs. Any class with default constructor, Init, and Deinit is badly polluted.
It's written in C++, has strict coding guidelines, and mostly free of bloat.
I would start by reading the LLVM Programmer's Manual [prog man] and the LLVM Coding Standards [code stand] and looking up how the code they reference and the examples are implemented and how they interact with each other. You can browse the code in the LLVM Mirror Git repository [llvm-git] or the cross-referenced Doxygen [llvm-doxy] (has very useful links!). If you're willing to spend the time it might be worth setting up the codebase in your IDE of choice with the proper integrations to be able to browse and cross-reference the source code there.
There is a lot to learn especially from the Important and useful LLVM APIs and Picking the Right Data Structure for a Task (and the corresponding code) in the Programmer's Manual. The data structures under llvm/ADT could be especially useful to look at. They are good generic data structures that you may even want to directly reuse in your own project, but they are much easier on the eyes and closer to what you and I would want to see in our own codebases than the source code of the standard library or the Boost data structures.
[prog man]: https://releases.llvm.org/4.0.1/docs/ProgrammersManual.html
[code stand]: https://releases.llvm.org/4.0.1/docs/CodingStandards.html
[llvm-git]: https://github.com/llvm-mirror/llvm
[llvm-doxy]: http://llvm.org/doxygen/modules.html
PS. The Coding Standards will contain a lot of subjective stuff that makes sense inside LLVM for consistency but you don't want to adopt verbatim into an existing (maybe not even a green field) project, like naming variables with Capital letters. You can skim these parts, but it might be useful to know about the existence of these types of issues.
- WebKit - Chrome
Also Google's Abseil, very modern C++ patterns and containing some unexpectedly deep designs for apparently simple things. https://source.chromium.org/chromium/chromium/src/+/master:t...
I had a quick look at the code but I would be interested in what "a style that is something between C and C++" actually entails.
Avoiding templates but using classes/namespaces? Minimizing use of the stl?
Also while ImGUI is great and the guy follows good coding practices - it's not at all what I would recommend for learning C++. Not only is it technically not C++, but the problem it solves (GUI-Framework and immediate on top) leads to some pretty hard to follow code with a lot of hidden global state.
I'm going to have nightmares tonight.
The code base is quite simple and readable, because it consists of several self-contained modules, many of which are just wrappers around existing libraries.
For a "professional" code base, you could have a look at JUCE, which is also very modular: https://github.com/juce-framework/JUCE
Both projects are written in "modern C++" (C++11 and above).
Take a look at these:
I do agree that the field is full of great code to reference, though.
I'm a huge fan of Godot's codebase. It's well written, and easily understood both architecturally, and in-method. https://github.com/godotengine/godot
There are some pretty good public game codebases (Penumbra/HPL, Quake I/II/III, Doom I/III), there are some okay ones (RedAlert), there are also pretty awful ones (Duke3D, Descent).
Note that this seems to be completely independent from whether the game is good or not!
I wouldn't say it's particularly "clean", given the constraints on the project, but it does do a lot of things that are interesting from a security/DoS perspective. There are even some SDR related work being done recently for alternative relays!
WSPR: https://youtu.be/QkYXPJMqBNk?t=4974
Blockstream Sat: https://github.com/Blockstream/satellite
So when you have a chance you could take a look at this link that lists one-to-two files libraries: https://github.com/nothings/single_file_libs
I think I came across the link above here on HN a couple of weeks ago.
I also study some of the libs from here: https://github.com/fffaraz/awesome-cpp.
Currently I'm going trough the libs for parsing CSV files. Of them, I find this one particularly interesting: https://github.com/vincentlaucsb/csv-parser. Because of well-commented files.
I hope it helps.
I'm also looking into Inversion of Control/Dependency injection containers.
And never forget to look at C++ Core guidelines: https://isocpp.org/guidelines
In my experience, the stuff in C++ from Microsoft and Google are great resources to learn, so i would give a especial mention to (in order of C++ awesomeness):
Dart VM
Chakra VM
V8 VM
Chrome
LevelDb
WebKit
(*) Doom 3 engine
* - Doom 3 is not very modern by today standards, but the way the code is composed, the things relate among themselves, etc, are a great resource of learning.* - Didnt dig much into the most modern stuff from Mozilla, so i dont know how it is actually. Back in the day, there were a lot of legacy from their older codebases, so i dont now how the more modern stuff are, but im almost sure they might look great.
positionSlider.onValueChange = [this]() { seekVideoToNormalisedPosition (positionSlider.getValue()); };
[things-to-capture](params) -> return-type { function-body; }
The return type is optional [0] since it can be detected automatically. The things-to-capture have a couple variants: [&foo]...
Captures variable foo by reference. [foo]...
Makes a copy of foo.You can also capture "everything" using [&] or [=]. Handy if you don't want to make an explicit list of captured variables. You can also mix it:
[&foo, bar]...
Captures foo by reference and a copy of bar.https://en.cppreference.com/w/cpp/language/lambda
[0] Additionally, lambdas may not have a return value. Like this one:
int n = 0;
auto counter = [&n] () { n++; }
counter();
// now n == 1Now I'm having a lot of fun, still learning, while programming the ESP8266 and especially the ESP32 (via PlatformIO). Playing with Wifi and Bluetooth too.
The best thing in my view about learning things with micro controllers is the 'tangible' result. Seeing things happen or move. (or not! and why.)
I thoroughly recommend it, along with all the other responses here.
- SFML is a simple, fast, cross-platform and object-oriented multimedia API. It provides access to windowing, graphics, audio and network. https://github.com/SFML/SFML
https://github.com/lballabio/QuantLib
Also, there is a book which describes the different patterns used:
The abstractions that are built up within that codebase feel very clean, like they get out of your way so that you can be productive, without drowning you in syntax.
https://gameprogrammingpatterns.com/
Examples are in C++ and the prose is also far more friendly than standard academic texts.
I haven’t looked at it but from Jason Turners’ videos I know he uses the modernize and cpp core guidelines checks with clang tidy on it so it should be modern c++.
Abseil.
I work in Chromium all day long, so I'd like to say that, but it's also huge and has... complexities.
It's written in Qt, but still uses "normal" C++ for a lot of stuff.
Amazing codebase by an amazing developer and maintainer.
* Classic C++ (before C++11) * Modern C++ (after C++11) * Object oriented C++ * Functional C++ * Metaprogramming (Template) C++ * I am sure there are more examples...
There is also whether you plan to use a specific library or not.
For example I have used Qt for a long time and never touched the STD (standard library) or STL (standard template library). Qt has its own Qt way of doing things.
You might need to be more specific as to which is the dommain that you want to apply C++.
It's almost impossible to use multiple libraries together without wrapping everything in one's own "house" style as a consequence.
In contrast, languages like Java and Rust, for example, have one single standard way of doing things that 99% of people just follow.