6 Useful New Features in C++17 – Part 3

This is the third part of the series “6 Useful New Features in C++17”, the first part can be found here.

Init statements in if statements

Like for statements, if and switch statements get an initializer part. Convenient when handling shared resources between threads. As an example, if there are a lot of workers that share a single job queue but the jobs themselves are independent, then we only want to block while popping the queue and not while executing the job. One could solve this with the following:

The extra scope makes sure that we release the guard after we successfully grabbed a job to process. In my opinion it looks a bit messy and we’ve added extra parentheses to keep track of. If we instead make use of the init statement it could be rewritten as follows:

At least I think this is easier to follow and less error prone while refactoring.

Compiler Support

These features are all fully supported by GCC, MSVC, and clang. Below follows a table showing which version enables support for each feature respectively.

For more a detailed matrix with more compilers and all features of C++17 listed, follow this link.

 

READ PART 4 “6 Useful New Features in C++17” HERE.

 

// Patrik Ingmarsson