C++11 Guide: A Practical Guide for the Everyday Programmer
https://stuartwheaton.com/blog/2020-06-14-c++11-guide/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() consttype functions (which are defaulted tofalsein 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() constremain?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
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, anddiff -uproduces 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
finalkeyword allows you to avoid indirection via the vtable when it's not necessary.Just don't declare those function virtual, only
overrideand that's it.? All
overridefunctions 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
finalproduces different assembly: https://godbolt.org/z/vXoXJ62
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
virtualkeyword. Assumedfinalunless marked asvirtual.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:
5
u/dodheim Jun 16 '20
If they are all virtual when override then ...
Even without
virtualoroverride, any member function in a derived class that matches the signature of a virtual member function in a base is itself implicitly virtual.overridewas added to the language to reduce confusion when opted-into, butoverrideis 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-overrideoption. Not sure.if it's part of-Wallor-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
overridefor any member function, while having other virtual functions not similarly annotated.1
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
virtualkeyword 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
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
1
1
26
u/manni66 Jun 16 '20
C++11 posted on June 14, 2020?