Thursday, January 26, 2017

C++ tips, 2017 Week 3 (16-Jan - 22-Jan-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::is_trivially_copyable

std::is_trivially_copyable tests a type (or a C-style array) if its a TriviallyCopyable type. In short this means if you can and you are allowed to just memcpy one object into another. "If you can" (obviously you can memcpy everything but...) means that the type does not have virtual member function, virtual base class or any non-trivial (user provided) copy/move operations or destructor. Providing any user defined copy/move operation or destructor signals the compiler that there is something special about this type and it should avoid some optimizations. "You are allowed" means that at least one move/copy operations is not deleted and the destructor is not deleted too.

Thursday, January 19, 2017

C++ tips, 2017 Week 2 (9-Jan - 15-Jan-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::forward

std::forward helps ... forward a T&& function argument as-is to another function. In the following example:
template<class T>
void choose_foo(T&& arg)
{
   foo(arg);
}
arg is treated as lvalue and will call the T& overload of foo. However if we pass a temporary to choose_foo we probably want to call the T&& overload of foo (if any). To fix this we use std::forward:
template<class T>
void choose_foo(T&& u)
{
   foo(std::forward<T>(u));
}

Wednesday, January 11, 2017

C++ tips, 2017 Week 1 (2-Jan - 8-Jan-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. No raw  loops

If you have watched Sean Parent's great talk C++ seasoning you know the goal No raw loop (if you haven't - go and watch it). In short - always try to not use raw loops.

The rationale behind this is simple. When you are using raw loops you are usually iterating over something. Most likely it will be a container. Most likely it will be a std or boost container in which case you are going to use iterators. And since you are doing something while iterating over the container with those iterators it is most likely something already implemented in the <algorithm> library - either being finding, for_each-ing, merging, copying, sorting, filtering, etc.