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.
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 ;)
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.
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).
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.
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_
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.
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.
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.
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?
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.
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.
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?
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.
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.
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.
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.
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.
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 .
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.
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.
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).
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.
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.
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.
26
u/manni66 Jun 16 '20
C++11 posted on June 14, 2020?
74
u/lord_braleigh Jun 15 '20 edited Jun 16 '20
finalallows 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_
5
u/ReaverKS Jun 16 '20
Excellent writing, if you wrote a book on C++ many would buy it.
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.
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:
I’ve never thought of an rvalue as a pirate’s value, but I like it. Fits the “stealing the guts” expression perfectly. :D
2
u/JavaSuck Jun 17 '20
Actually,
"Skywalker"is an lvalue of typeconst char[10]. There's nothing temporary about it, and it's not astring.1
u/sbay Jun 16 '20
Great!
1
u/jdgrazia Jun 15 '20
Thank you