Friday, February 10, 2017

C++ tips, 2017 Week 5 (30-Jan - 5-Feb-2017)

This is part of my weekly C++ posts based on the daily C++ tips I make at my work. I strongly recommend this practice. If you dont have it in your company start it. 
List of all weekly posts can be found here.

1. std::size, data, empty

From C++17 we are getting the free functions std::size, std::data, std::empty. They are similar to the free functions std::begin and std::end and if used with standard container just call the corresponding member function and work for C-style arrays if it makes sense. Possible std::size implementation for C-style arrays (container one just returns .size()):

(lets try GitHub Gist because Blogger formatting is driving me nuts)


As with std::begin and std::end the advice is to prefer the free functions for several reasons - above all they are constexpr and always inlined by a modern compiler, they work with C-style arrays and if you happen to use a custom container with different interface you can specialize the free functions to work with it without modifying existing code.

2. thread_local

thread_local is a storage class specifier indicating that the object has a thread storage duration meaning that the object is allocated when the thread begins and deallocated when the thread ends. It can be combined with static or extern to specify linkage. In short - it makes global/static objects localized to the thread they are used.

Typical use case is generating random numbers. Instead of guarding one global random generator with mutexes for thread safety we just create one static thread_local for each thread (memory for speed tread-off):



3. std::array

std::array is the modern upgrade of C-style array - all the benefits plus standard container behavior minus the automatic decay to T* and after that unknown size. Also it has constexpr everywhere so in theory the compiler should do as much as possible at compile time when using std::array.



(thanks to Francisco Lopes for pointing me an error in this example)

As we saw couple weeks ago it is a trivially copyable (you can memcpy it) type exactly what one would expect from a C-style array replacement.

So if the size of the vector/list/deck/etc is known at compile time use std::array instead - do not pay for functionality you do not use.

4. Self imposed deadlines

A deadline is a deadline - I decided to prioritize one-post-per-week more than five-tips-per-post. So I'll stop here. Totally selfishly I want to catch the Jens Weller's weekly C++ Blogroll train too.

Jens, thanks a lot for sharing my posts!



No comments:

Post a Comment