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)

  1. When overriding methods, use void Method() override; instead of virtual void Method(). (original video says use both virtual and override but this is redundant as override implies virtual)

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.

  1. Explicit type for enum: enum MyEnum : uint32_t { ... };. Does not require enum class.

  2. Prefer using NewType = OldType to typedef OldType NewType (so that it’s obvious which type is your NewType — not so much when function pointers and arrays are involved in the typedef 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.

  1. Struct/class member fields can have in-line default values: struct A { int x = 1; int y = 2; };.

  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.

  1. 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.

  1. explicit operator bool

  2. static_assert is now standard (no more macro needed)

  3. #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.

Written on August 29, 2018, Last update on May 29, 2023
c++