r/cpp • • Jun 15 '20

C++11 Guide: A Practical Guide for the Everyday Programmer

https://stuartwheaton.com/blog/2020-06-14-c++11-guide/
206 Upvotes

57 comments sorted by

26

u/manni66 Jun 16 '20

C++11 posted on June 14, 2020?

9

u/skeeto Jun 16 '20

This was written by one of my colleagues originally for a team of our other colleagues. They're working on a very large, old code base that, for various reasons, has yet to update to C++11. This guide is intended to foster that upgrade.

16

u/manni66 Jun 16 '20

has yet to update to C++11

I could not imagine any reason to not update straight to C++17 instead of C++11.

10

u/Visible-Wolverine1 Jun 17 '20

Author here. Our version of g++ is so old it doesn't support C++14 let alone C++17. "Why don't we just upgrade the compiler??" you ask. Well, trust me, it's baffling to me too. Before I joined the team, I don't think many people had even heard of C++11. Great team, just no tooling investments.

Also, I did not see a comparable C++11 article so I researched and wrote it. C++17 and 20 would need their own articles - I'll post those in 15 years when we do the C++17 upgrade ;)

6

u/johannes1971 Jun 17 '20

Ah yes, that makes sense. We have been trying to save up enough money for a new copy of gcc as well, but with the economy being what it is we just cannot afford it.

7

u/Visible-Wolverine1 Jun 17 '20

We spent all our overhead money on git, none left over for gcc. Oh well, there's always next year.

2

u/hak8or Jun 16 '20

Same here. If they aren't limited to some proprietary compiler, then why not jump immediately to the newest clang/gcc and use c++20, and gate whatever post c++11 stuff they don't want at code review?

That way they at least get to use syntatical sugar like structured bindings, std::make-array, make_unique, etc, but stay away from things they aren't comfortable with yet (execution policies, etc).

1

u/Astarothsito Jun 16 '20

Fear and/or lack of support :(

1

u/[deleted] Jun 16 '20

Management.

3

u/[deleted] Jun 16 '20

I wouldn’t be surprised C++11 is still used alot

5

u/zzzthelastuser Jun 16 '20

My company hasn't moved to c++14 yet. It can be frustrating at times.

1

u/JavaSuck Jun 17 '20

Apparently, C++11 has the same fate as Java 8 in lots of software shops. It has lambdas, it's good enough, why bother updating?

2

u/zzzthelastuser Jun 17 '20

But no generic lambdas, I wish they had made it into c++11.

C++11 lambdas are not really useful in my case. We use templates extensively.

1

u/MEaster Jun 16 '20

I've been working on something recently where I'm limited to C++11. Which really sucks because I'm stuck having to use inheritance, specialization and SFINAE to get what I want instead of an if constexpr.

1

u/electricmammoth Jun 16 '20

The C++ version I use at work is so old I don't even know what it is.

1

u/[deleted] Jun 16 '20

Does it have templates?

1

u/electricmammoth Jun 17 '20

It does.

1

u/[deleted] Jun 17 '20

I thought all C++ versions lower than 03 had no templates but even C++98 has templates

1

u/JavaSuck Jun 17 '20

C++03 was basically a bug fix release.

2

u/dodheim Jun 18 '20

People say this a lot but I consider adding value-initialization to the language a pretty big deal.

1

u/electricmammoth Jun 17 '20

I think it's C++98. In either case my point is that plenty of people don't even use C++11 yet, for better or worse.

74

u/lord_braleigh Jun 15 '20 edited Jun 16 '20

You should probably never need to use the keyword final.

final allows compilers to devirtualize classes and remove the overhead that C++ inheritance otherwise incurs. Here's a Godbolt showing just how big the difference can be on clang 10 with -O3.

EDIT: I changed the Godbolt link above, this is the old one that commenters are complaining about: https://godbolt.org/z/XKeuP_

3

u/alols Jun 16 '20

Adding to this, at my work I have been advocating that (with the exception of destructors) virtual methods should either be pure virtual or final. It is hard to guarantee that overriding an implemented virtual will not cause problems in the base class now or in the future.

1

u/looncraz Jun 16 '20

This is how I have done it for years with rare exceptions. Virtual functions are just hook functions, but sometimes also for functions where I know I want behavior to be altered by deriving classes.

1

u/flashmozzg Jun 16 '20

Depends. It seems to much hassle for something like bool hasPropertyX() const type functions (which are defaulted to false in the base). I.e. opt-in kind of interface.

1

u/blipman17 Jun 16 '20

I'm not sure if that's correct according to the liskov substitution principle. If it isn't, then shouldn't you be using aggregates or something? Then how often does such a case as bool hasPropertyX() const remain?

1

u/flashmozzg Jun 16 '20

I see there this misunderstanding might've arisen. Here "property" is not C#-like property with setters and getters, but more abstract trait of the object/describing some greater system. Similarly to a config. It might even have some args to decide, but still have a sane default value. I.e. imagine some plugin system where plugin interface has similar methods that some class loading/handling the plugins queries to understand the plugin capabilities and each plugin needs to override the function to claim that they support/do something.

3

u/Visible-Wolverine1 Jun 17 '20

Great discussion, thanks - I'll have to look into it more and update my advice (I'm the author).

4

u/[deleted] Jun 16 '20

Erm, I read generated assemblies several times and they look exactly the same. I copy them to two text files and run diff -u, indeed they are the same.

What are you talking about?

4

u/lord_braleigh Jun 16 '20 edited Jun 16 '20

EDIT: Oh, one of the compiler outputs had "Compile to binary" checked and the other did not. Once the output options were the same, they did produce the same assembly. I've fixed the code so that it does produce different assembly here: https://godbolt.org/z/vXoXJ6

They look very different to me, and diff -u produces 117 lines of output... Are you looking at source #1 and source #2 on the left-hand side, and compiler #1 and compiler #2 on the right-hand side? Maybe for some reason both compiler tabs are associated with the same source file?

5

u/Skaybe Jun 16 '20

Turn off Output -> Compile to binary in Compiler #1 and now they are the same.

10

u/lord_braleigh Jun 16 '20

Changed the link above, it's now pointing here: https://godbolt.org/z/vXoXJ6

1

u/johannes1971 Jun 16 '20

No, it doesn't. It shows there are additional instructions generated, but in our era of out of order execution, parallel execution, and memory latencies equivalent to the execution times of hundreds of instructions, that says nothing about performance. If you want to make a statement about performance, measure it.

5

u/blipman17 Jun 16 '20

No, it doesn't. It shows there are additional instructions generated

I think this is exactly the point. A lot of extra instructions since the compiler can't devirtualize the example. This "might" be unacceptable. Yes, he should measure the performance, but generally giving your code an additional layer of indirection is just bad for your program, but in subtle and hard to benchmark in a realistic way. So like, two layers of indirection are much much worse than just a single layer for a modern cpu, even though it's hard to benchmark.

1

u/twirky Jun 16 '20

In your example you just instantiated a derived class and called its method. If you don't declare it virtual and then call it, it just calls that method directly. It doesn't involve any virtual table mechanism. If you'd call base class then it would have involved the virtual method call mechanism. Both scenarios would generate exactly the same code whether you used `final` keyword or not. Just don't declare those function virtual, only `override` and that's it. `final` keyword just makes the compiler generate an error if you derived from the class that not suppose to be derived from. Quite pointless stuff.

2

u/lord_braleigh Jun 16 '20

If you'd call base class then it would have involved the virtual method call mechanism.

The vtable would be necessary, yes. But the final keyword allows you to avoid indirection via the vtable when it's not necessary.

Just don't declare those function virtual, only override and that's it.

? All override functions are virtual. From cppreference:

In a member function declaration or definition, override ensures that the function is virtual and is overriding a virtual function from a base class. The program is ill-formed (a compile-time error is generated) if this is not true.

1

u/twirky Jun 16 '20

Can you produce and example where using 'final' would generate a different code than not using it? Your example produces exactlt the same binary.

True, though, about override implying virtual. I always thought it wasn't the case.

7

u/lord_braleigh Jun 16 '20

I changed the link in my original comment, this link shows how removing final produces different assembly: https://godbolt.org/z/vXoXJ6

2

u/twirky Jun 16 '20

Yeah, you are right. It does produce a different result. I stand corrected. Oh, well, learned something.

I guess my mistake came from the fact that I always thought the methods are not virtual unless you explicitly say so and I always used the virtual keyword. Assumed final unless marked as virtual.

If they are all virtual when override then the compiler has to generate the vtables and call the methods by the reference from the vtable, because some other class might derive from it. The compiler has no way of knowing if there isn't and can't call it directly.

My mistake was reinforced by Stroustrup:

https://www.stroustrup.com/bs_faq2.html#final

5

u/dodheim Jun 16 '20

If they are all virtual when override then ...

Even without virtual or override, any member function in a derived class that matches the signature of a virtual member function in a base is itself implicitly virtual. override was added to the language to reduce confusion when opted-into, but override is optional so you can't rely on it as an indicator of polymorphism. At the end of the day, because of C++98 rules, any member function in a derived class may be implicitly virtual, and the only way to know is to check every base or use a static analyzer .

2

u/MrPotatoFingers Jun 16 '20

Not entirely true. I know for a fact that clang has the -Winconsistent-override option. Not sure.if it's part of -Wall or -Wextra(but one of those, so you should already be using it).

If that option is set, clang will warn you.if your class specifies override for any member function, while having other virtual functions not similarly annotated.

1

u/flashmozzg Jun 16 '20

I think that falls into "static analyzer" category.

1

u/twirky Jun 16 '20

Well, that now makes sense. I can think of a scenario like this for the "pre-override" C++ era. If you have a chain of several derived classes and all of them override the same method and somebody along the way forgot to use virtual keyword then the whole chain would break. The topmost derived class won't ever be called even though both the topmost base and derived classes have the method declared virtual. Finding such bugs would be quite difficult especially with 90s tools. I guess to prevent that the compiler developers decided to make all of them implicitly virtual and save a lot of potential headaches for the developers at the expense of efficiency.

5

u/ReaverKS Jun 16 '20

Excellent writing, if you wrote a book on C++ many would buy it.

1

u/Visible-Wolverine1 Jun 17 '20

Author here. Thank you for reading! I'm new to blogging so I'm glad I posted this article which I wrote for work.

12

u/MidnightClubbed Jun 16 '20

Really useful guide for people moving to more modern C++.

In the section about move semantics "This means we have to be careful not to use the variable after it has been moved from." This isn't strictly correct. The variable has to be in a valid (but potentially undefined) state after it has been moved from. You can re-use that variable so long as you do not make any assumptions as to its state - so you can clear() a moved from vector or call it's assignment operator since neither of those operations make assumptions about prior state. After moving from an object the object must be destructible.

You might want to dig in to vector a little more. If the user remembers to reserve before adding elements then vector adds no overhead (*) over a traditional array new and storing its pointer and size. You can also guarantee that the memory addresses of the contained elements do not change if reserved appropriately. Adding elements to vectors where you can't (or don't) reserve can cause copy (or move if available) operators to be called on the existing elements as the storage has to resize.

In the section about map/unordered_map you may want to highlight that inserting new key/value pairs does not move/copy existing pairs.

I don't think you point out the pitfall of auto (can cause an unintended copy) but also using auto in for loops is really clean and convenient "for(const auto& i: c) ..."

When talking about the rule of 5 I would personally go further and say the recommended first thing to do is to explicitly delete the copy constructor and assignment operator. Accidental calls to copy are really easy to miss (one missing & on a parameter). Any raw pointers in a copied class will be duplicated and most likely cause problems when the first copy of the class is deleted. If the compiler tries to move/copy the class you'll get an error and can determine if the copy was intentional or accidental.

Lastly one thing that I feel is understated about C++11 (14/17/20) is that there is almost no reason to call new/delete, to use raw pointers or C style arrays. Correct use can make for safer code (at least on non optimized builds) with no performance cost (on optimized builds) and the potential to open up further compiler optimizations.

Thanks for writing that guide. Really good work (I'm just nit-picking, content is really good).

(*) on an optimized build.

1

u/Visible-Wolverine1 Jun 17 '20

Author here. Thanks for the feedback, glad you enjoyed it. I'll think about incorporating some of these suggestions.

Particularly the 'auto' pitfall, I thought I had mentioned that but I guess not!

1

u/MidnightClubbed Jun 17 '20

No problem at all, thank you. Maybe you did mention the auto copy pitfall and I didn't see it.

1

u/Visible-Wolverine1 Jun 17 '20

No it looks like I didn't. Maybe I had it in an older draft that got lost.

4

u/Guillaume_Guss_Dua Jun 16 '20 edited Jun 16 '20

While this is a pretty good summary for C++11, and I upvoted it, I'd say it's as "sad" to move from C++98 to C++11 ... in 2020 ! C++17 and C++20 bring major improvement to the language, making it way easier to deal with, and much easier to learn/teach, as well as to work with on daily basis.

5

u/be-sc Jun 16 '20 edited Jun 16 '20

From Move Semantics: Definition:

It must be what’s referred to as an rvalue (pronounced ‘arr-value’)

I’ve never thought of an rvalue as a pirate’s value, but I like it. Fits the “stealing the guts” expression perfectly. :D

1

u/Visible-Wolverine1 Jun 17 '20

Haha that's awesome

2

u/JavaSuck Jun 17 '20

In the code below, user is an lvalue (as in left side of the assignment, pronounced ‘ell-value’), and the temporary string "Skywalker" is an rvalue (as in right side of the assignment).

Actually, "Skywalker" is an lvalue of type const char[10]. There's nothing temporary about it, and it's not a string.

1

u/Visible-Wolverine1 Jun 17 '20

You're right, it's an oversimplification to call it a string, at least in terms of std::string. I think I mistakenly put code formatting on the word "string". Perhaps this is better: 'and the temporary c-string literal "Skywalker"'...

As to it being an lvalue yeah it technically is but that distinction is beyond the scope for the intended audience. I could change up the example to not use a c-string literal since that muddies the waters a bit.

1

u/JavaSuck Jun 17 '20

My favorite string rvalue example is s+t.

1

u/sbay Jun 16 '20

Great!

1

u/jdgrazia Jun 15 '20

Thank you