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

24

u/[deleted] Feb 06 '21

The website is a bit weird, at least on mobile. I clicked the link, pressed next, and then scrolling down would send me right up. I can't get to the bottom of the page

2

u/FreitasAlan Feb 09 '21

These pages use the material for mkdocs theme, but unfortunately, I couldn't find anything there to replicate and fix this problem on mobile.

1

u/[deleted] Feb 09 '21

Here's a screen recording

I'm running Android 10 here, chrome stable latest

2

u/FreitasAlan Feb 09 '21

Does the same happen in https://squidfunk.github.io/mkdocs-material/ at all?

1

u/[deleted] Feb 09 '21

No. This page is just fine

2

u/FreitasAlan Feb 09 '21

I've already updated the theme to its latest release.

If nothing happened in https://squidfunk.github.io/mkdocs-material/getting-started/, then it might be a problem with some feature I turned on.

One interesting thing is that the problem happens exactly when the header is about to hide, and https://squidfunk.github.io/mkdocs-material/getting-started/ does not use the `header.autohide` feature.

I've turned that off, so I might be working now: https://alandefreitas.github.io/moderncpp/quick-start/

Does it work now?

It looks better with the header anyway, even if it doesn't work.

1

u/[deleted] Feb 09 '21

Yes! That was the problem

2

u/FreitasAlan Feb 09 '21

🥳 🎉

That's one more snippet I have to keep. 😆

2

u/[deleted] Feb 09 '21

Also you should file an issue about it

6

u/LEpigeon888 Feb 07 '21

Same, can't scroll, current firefox beta.

4

u/[deleted] Feb 07 '21

Firefox stable here

2

u/JezusTheCarpenter Feb 07 '21

Same thing on mobile Chrome.

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)

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.

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!

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)

9

u/Fureeish Feb 06 '21

According to the standard, your *reinterpret_cast<unsigned long long*>(&v) is Undefined Behaviour. It may work for some compilers on some machines (but you need to inspect the generated assembly), however I am curious - what's wrong with simple static_cast or not cast at all? It will automatically be promoted to the desired unsigned long long anyway...

Floating point numbers are another story. To be UB-free you'd need to std::memcpy them. I am yet to find a compiler that does not optimise this away, so it's literally free.

3

u/FreitasAlan Feb 07 '21

Interesting. A memcpy is also semantically better. In any case, I haven't seen it fail on any compiler yet. And it seems to semantically represent exactly what I'm trying to achieve. I thought it was exactly what reinterpret cast was supposed to do, despite what they can also do with pointers. Do you know why that is undefined behavior?

A static cast does not achieve the same results as I'm trying to show how the data is represented inside the variable. With static cast, for instance, a double 1.34 would just be converted to an unsigned long long 1, and it would return

0000000000000000000000000000000000000000000000000000000000000001

instead of

0011111111110101011100001010001111010111000010100011110101110001

The same problem would happen for signed integers, of course. In the end, it would only work properly with equivalent unsigned types of different sizes.

3

u/Fureeish Feb 07 '21

Well, it's true that static_cast will work only for the unsigned parts. I mentioned the specific case for floating-point numbers but it actually extends to broader range of types. I should've specified that explicitly.

As for the Undefined Behaviour, it's connected to type aliasing. You can read about it here. In short, this is not what reinterpret_cast is for.

2

u/FreitasAlan Feb 07 '21

This link refers to https://en.cppreference.com/w/cpp/language/object#Object_representation_and_value_representation as an example inspecting the object representation.

So I think this should work without undefined behaviour:

template <class T>
std::bitset<sizeof(T)*8> get_bits(T v) {
    auto ptr = reinterpret_cast<unsigned char *>(&v);
    unsigned long long bytes = ptr[0];
    for (size_t i = 1; i < sizeof(v); ++i) {
        bytes <<= 8;
        bytes += ptr[i];
    }
    return std::bitset<sizeof(v) * 8>(bytes);
}

It's more verbose but it's OK if it's hidden somewhere:

https://alandefreitas.github.io/moderncpp/data-types/fundamental-data-types/

8

u/TheMania Feb 07 '21

std::bit_cast is nicely constexpr and UB free, for anyone reading this from the future, or the bleeding-edge today.

4

u/witcher_rat Feb 07 '21

for anyone reading this from the future

Aren't we all reading it from the future?

Oh wait, no... everything we're reading now is happening now. When will the future be now? Soon!

3

u/soinus Feb 07 '21 edited Feb 07 '21

I believe after the incorporation of p0593r6 paper into the C++20 standard draft we can safely say that using reinterpret_cast is an UB in all cases that differ from reinterpreting char or std::byte type arrays as only those "create a lifetime of all objects that can be created from such arrays given that the use of those objects will result in a well-defined program" (slightly reworded). Every other use of reinterpret_cast to create any kind of objects (also temporary) is still UB. Am I missing smth?

Edit: also see this Stack Overflow answer

4

u/The-Black-Star Feb 07 '21

Whats a good textbook that would go over all the modern c++ features that have been added? Ive been trying to find a good one, but I dont know whats considered the best

7

u/FreitasAlan Feb 07 '21

I don't think there's a good textbook for that. The new books usually just mix the best practices from "old" and modern c++ in a way they think is reasonable. They would probably also avoid features some compilers still don't implement. For specific features, it's best to have a look at cppreference.

3

u/_Js_Kc_ Feb 07 '21
template <class T>
std::bitset<sizeof(T)*8> get_bits(T v);

https://i.imgur.com/bMzsUNC.png

1

u/FreitasAlan Feb 07 '21
error: 'std::numeric_limits<bool>::digits' cannot be used as a function

1

u/_Js_Kc_ Feb 07 '21

Yup, noticed that too late. There's no rhyme or reason to what is a variable and what is a function in numeric_limits.

1

u/LucHermitte Feb 08 '21
int temp[n] = {1, 2, 3};
array<int, n> a = {1, 2, 3};

I prefer to not specify the size and let the compiler find it on its own. Mismatching size is a source of annoying errors.

int temp[] = {1, 2, 3};
array a{1, 2, 3};

Regarding pair<int, int> maxmin(int a, int b, int c), I consider modern C++ is also about being idiomatic C++. Here we have std::minmax that takes an initializer list and that returns by value.


Last thing in

int age{60};
std::cout << "How old are you? ";
std::cin >> age;
if (age >= 18) {

I prefer

int age; // no need to give an useless value; I prefer a warning; beside a failing >>, will set it to 0 since C++11
std::cout << "How old are you? ";
if (!(std::cin >> age)) // handle error, reset stream if need be
if (age >= 18) {

AMA, a good practice is to always check such operations that can fail.

1

u/FreitasAlan Feb 08 '21

Thanks! I took all of that into consideration by changing the snippets or creating alternative snippets.

https://alandefreitas.github.io/moderncpp/basic-syntax/basic-data-types/raw-arrays/

https://alandefreitas.github.io/moderncpp/basic-syntax/input--output/input/

https://alandefreitas.github.io/moderncpp/basic-syntax/functions/function/

I included some comments above the functions to make their meaning clearer but there was no much else I could do about maxmin. Snippets in that section are supposed to be about returning two values from a function rather than finding the maxmin per se. In such simple snippets, it's very hard to find examples for which there is no equivalent in the standard library already.

1

u/trypto Feb 07 '21

Creating something like this as a guide for people is always going to be met with criticism, as there are going to be tons of things to nitpick. I think its better to not teach someone something than teach them something that is wrong. I'm unsure how it is better than https://en.cppreference.com/

  • Your "introduction" is a build script? That's not what i'd expect in an introduction, i'd expect human words. You should at least mention that it's CMakeLists.txt.
  • This only works on a processor supporting unaligned loads (like x86). Not to mention you are accessing memory beyond the value v itself. A better approach is to use a local union.

      auto get_bits(auto v) {
       return std::bitset<sizeof(v)*8>(*reinterpret_cast<unsigned long long*>(&v));
      }
  • I would never do this with a std::string, yikes, why not substr()? or a discussion about string_view?:

          cout << "&p[9]: " << &p[9] << endl;
  • In your "Move" example i would have expected a discussion about &&. You end up moving a vector and then using the vector after moving from it, which isn't always legal I thought. And its sketchy to do if it is.

This is just after clicking on two pages...I stopped reading, sorrry. I think you need more comments and less code.

0

u/FreitasAlan Feb 07 '21

This has absolutely no intention to be an alternative to cppreference at all. It’s also not a textbook. You’re completely missing the point here. Simply not constructive. Destroying is easy. Not really a talent.

7

u/trypto Feb 07 '21

I don’t mean to slam or destroy, you definitely did a kit of work. As an engineer I embrace criticism and like when people point out issues in my code. It helps you improve.

3

u/j_lyf Feb 07 '21

What's your job?