Easing into Modern C++
C++ has changed a lot in recent years. The last two revisions, C++11 and C++14, introduce so many new features that, in the words of Bjarne Stroustrup, “It feels like a new language.” - C++ Has Become More Pythonic
video transcript (SO)
- When overriding methods, use
void Method() override;
instead ofvirtual void Method()
. (original video says use bothvirtual
andoverride
but this is redundant asoverride
impliesvirtual
)
is great for catching subtle bugs. Forget a const/volatile qualified? override will catch it. inadvertently call of a int instead of a long? override will catch it.
-
Explicit type for enum:
enum MyEnum : uint32_t { ... };
. Does not requireenum class
. -
Prefer
using NewType = OldType
totypedef OldType NewType
(so that it’s obvious which type is yourNewType
— not so much when function pointers and arrays are involved in thetypedef
case).
is great for readability. Especially when the type you’re naming is complex. (I’m looking at you, Boost multi_index_container). The name comes first, the rest of the gobbledygook comes after what you’re looking for.
-
Struct/class member fields can have in-line default values:
struct A { int x = 1; int y = 2; };
. -
Explicitly
delete
constructors and assign operators.
is great - no longer need to inherit from boost::noncopyable or explicitly mark compiler supplied constructors/operators as private. Clearer intent. In the same vane, using default for, well, defaults. I see so much code like
struct Foo{ Foo(){} };
. The default is clearer to me as far as intent.
- Use
constexpr
functions to calculate compile-time constants instead of macros.
constexpr is valuable, but the example given in the video was kind of poor. It was already possible to get the array size using template metaprogramming at compile time in arguably simpler code than the example.
-
explicit operator bool
-
static_assert
is now standard (no more macro needed) -
#include <chrono>
for type-safe time
chrono is pretty great, but it’s support is spotty. It’s also not exactly user-friendly. Key formatting APIs are missing in long term supported versions of GCC in major Linux distros. (I’m currently on Ubuntu 14.04 w/ GCC 4.8 and, for example, it’s missing put_time). It’s usage is pretty cumbersome. I haven’t used it enough to have committed operations to memory, but things that would be 1 or 2 lines using Boost DateTime can be like 5-8 lines with chrono - not ideal.