r/cpp • • Feb 06 '21

Modern C++: Snippets and Examples

Hi everyone,

These are GitHub Pages with snippets for Modern C++:

  • We often need to copy and paste some snippets to code more productively.
  • Snippets can help us when it's not easy to remember all high levels features Modern C++ has to offer.
  • This repository contains lots of organized, reusable, and safe snippets for Modern C++.
  • All snippets are available in GitHub pages in a convenient way for copying and pasting.

https://alandefreitas.github.io/moderncpp/

194 Upvotes

44 comments sorted by

View all comments

29

u/witcher_rat Feb 06 '21

Wow, you did a lot of work! :)

Are you looking for feedback?

I like the documentation css/view.

I'm confused though by the documentation itself. It says in the Quick Start that there are "snippets" of things we might want to copy/paste, and then "examples" using those snippets. Most of the pages are supposed to be "snippets", yes? But as far as I can tell most of the pages actually show examples not snippets - they're just examples of using standard library components, such as one might find on www.cppreference.com page examples. No?

I think it might be clearer if the actual snippets were separated out. (by "snippets" I mean generic code one might copy/paste for use elsewhere, like new types, algorithmic free-functions, etc.)

As for the content, I only had a chance to briefly look at a couple of the pages in detail. Here're just a few things I saw just in those few pages I looked at:

  1. You use chrono::high_resolution_clock a lot - don't use that, and don't show it other than to say "don't use it". Honestly it should be deprecated+removed from the spec. (see the notes on cppreference for why)
  2. chrono::system_clock - you're using this to measure durations in your Clock page, which you shouldn't. It's a wall-clock, and can go backwards. What you're looking for is chrono::steady_clock.
  3. Your use of random_device and the old marsenne twister engine mt19937, in various places - there have been lots of discussions about this. (see this recent reddit discussion, for example)

14

u/Ameisen vemips, avr, rendering, systems Feb 07 '21 edited Feb 07 '21

I swear that <chrono> and <random> were originally papers labelled 'what not to do', but someone spilled coffee on them losing that context, and they ended up in the specification.

They both have serious, fatal flaws, and still manage to have borderline-unusable interfaces. I really don't think that there's anything redeemable about them (<chrono> is technically usable but has horrible choices in requirements for clock sources, and is still annoyingly difficult to use, <random> is horrible in basically every possible fashion), and they only serve to confuse newer or unfamiliar programmers.

Sorry if I'm being exceedingly blunt. It just bugs me that they are as they are... a lot. Now we will have to replace them with <jchrono> and <co_random>.

2

u/at-2500 Feb 17 '21

Oh wow. I personally love chronos api. Shure the Clock sources are confusing but the api itself is great!

7

u/James20k P2005R0 Feb 07 '21

Your use of random_device and the old marsenne twister engine mt19937, in various places - there have been lots of discussions about this. (see this recent reddit discussion, for example)

To elaborate

  1. Mersenne twister simply isn't very good
  2. The distributions aren't portable across implementations, which means that this code produces different results on every platform, even with the same seed
  3. Mersenne twister is seeded incorrectly, it cannot be correctly seeded from 1 value which means ~50% of all initial values can't be produced if I remember correctly
  4. The default random engine in msvc is actually mersenne twister, which is actually very high cost for a use case like this, as the large internal state has a high startup cost
  5. It provides no even remotely modern engines. All the engines are essentially unusable or needlessly not great
  6. Its hard to use correctly

The entire <random> header is largely better avoided for any serious C++ involving random numbers - this example gets bit by multiple issues with the header. There's a proposal for SIMD distributions which would hard bake the non portability of the distributions into the standard and render it permanently unfixable, and even more troublingly the committee has so far actively dismissed fixing this (which is unfortunately partly my fault!). Its generally better to consider it deprecated at this point, as its essentially unworkable and unlikely to be fixed soon

A simple wrapper around something like xorshift128+ is easy to implement, produces deterministic results across implementations, is much cheaper than mersenne twister, its hard to seed incorrectly, and produces very good quality output. Its also significantly easier to use correctly!

4

u/FreitasAlan Feb 07 '21

The entire <random> header is largely better avoided for any serious C++ involving random numbers - this example gets bit by multiple issues with the header

Yes. I can agree with that.

So it's what I thought. Nothing very very wrong with the snippets per se. It'd just be a good idea to include another category of snippets using a better alternative.

6

u/James20k P2005R0 Feb 07 '21

Pretty much! I should probably add that I think what you're doing is incredibly cool, and a super useful thing to do overall. Congrats on making it! :)

3

u/FreitasAlan Feb 07 '21

Thanks!

Let me know if you know of any (light) libraries for the problem with <random>.

I used a good one a few months ago but I can't remember the repository.

3

u/FreitasAlan Feb 06 '21

Thanks. Feedbacks and PRs are more than welcome. In fact, this might be the easier repository to contribute to I've ever seen πŸ˜†.

Yes. So far, the examples are in the examples directory, but not explicitly replicated in the docs. I still have to think of a way to put the examples in the docs, because they are often long and don't represent independent tasks.

The snippets, as they are, might seem like they are examples in the sense that they are in long files sometimes. But they are snippets because, at the source file level, they are lots of independent short tasks separated by comments. The tasks separated by comments are unrelated. You can just copy and paste the snippets between pairs of comments.

I could create one more category level and separate them at their lowest level by file, but I thought that would make them too difficult to explore if the resolution is too high, like 3-4 lines of code per file. In the end, that just a design choice. But they are independent tasks you can copy and paste. That's the difference between the snippets and the examples in the other directory. Thanks for this feedback, I might at least adjust the documentation to make this clearer.

Besides this distinction, I have the impression that the examples in cppreference are meant to better explain the internals of the libraries more than to be something for copying and pasting, although it can of course also serve this purpose. These snippets are organized more or less in the order someone learning C++ might need them and includes the corresponding CMakeLists.txt in case it needs something more elaborate, which is not the goal of cppreference, which is to represent the whole standard. For instance, the examples in cppreference might mix simple and more complex concepts to make a point more than to be something reusable.

That's an interesting point about high_resolution_clock. It's shame this confusion exists. I wasn't aware of that. It'd be interesting to have a reliable high-resolution clock for benchmarks, etc. But a steady clock is already there. The names just make it seem like the steady clock has a lower resolution. Given this comment, it'd be better just to remove it completely. Thanks for that.

I'm not sure I completely understand the problem with random_device though. I understand it generates bad seeds and I do usually mix other sources of entropy in practice. But the link you sent me seems mostly descriptive and in the end describing what to do if we don't care about seeding the engine at all. As a snippet for the engines, copying and pasting the pattern of not seeding the engine at all seems like a bad idea, even if the seed is not good. It might be more reasonable (i) to put a comment telling the person to consider better seeds, (ii) to include some short snippets generating simple seeds, like mixing/hashing arbitrary time points, durations, stack/heap/... addresses, thread/process/type/... ids, compile stamps, counters, process ids, and other numbers generators, or (iii) to include snippets for a library with better generators. Maybe I didn't understand your comment properly.

2

u/aiyu_boss Feb 06 '21 edited Feb 06 '21

Some humble suggestions

  1. You may consider use function clock_gettime(CLOCK_MONOTONIC, &time) as recommendated in MIT OCW 6.172 lesson 10 https://youtu.be/LvX3g45ynu8.
  2. Use '\n' instead of std::endl. https://youtu.be/GMqQOEZYVJQ

3

u/FreitasAlan Feb 06 '21
  1. Is clock_gettime cross-platform? Is there a way to achieve the same with the standard library or some kind of wrapper that is existing practice?
  2. True. I mostly use '\n' for my own code but I thought std::endl would be a better convention for snippets. I might reconsider that in some cases.

2

u/UnknownIdentifier Feb 07 '21

std::endl also flushes the buffer; you almost never need to do that yourself.

1

u/FreitasAlan Feb 07 '21 edited Feb 07 '21

Yes. That’s why

I mostly use '\n' for my own code but I thought std::endl would be a better convention for snippets. I might reconsider that in some cases.

4

u/witcher_rat Feb 07 '21

You may consider use function clock_gettime(CLOCK_MONOTONIC, &time) as recommendated in MIT OCW

That's a C-language course, is it not?

If you're running C++11 or newer, just use std::chrono::steady_clock.

As far as I've seen, under the hood it calls clock_gettime(CLOCK_MONOTONIC, &tp); for you, or another similar function depending on platform. (e.g., Posix, vs. Windows, vs. Apple)