Friday 4 October 2019

Initialization in modern C++

Initialization in C++ is unreasonably hard. There are 19 ways to initialize an int, leading to quite different results depending on the case. Copying initialization is a bogus. Move semantics makes all that ever more harder: https://www.youtube.com/watch?v=PNRju6_yn3o.

There are improvements coming in C++20 though: https://habr.com/ru/company/jugru/blog/469465/ related to homogenizing curly-braced and parenthesis initializations. This funny stuff is also fixed: https://youtu.be/AgatxxXNwBM?t=390 (in a funny way as well).

My own rule of thumb so far:
  • always avoid copy initialization,
  • use curly-braced initialization everywhere,
  • don't use parenthesis initialization.
That shall remain even with the coming of (args) and {args} homogenization in C++20, as {} prevents narrowing conversions which you usually don't want.

No comments:

Post a Comment