Hands-On High Performance Programming with Qt 5
上QQ阅读APP看书,第一时间看更新

Passing by value fashionable again

The introduction of move semantics slightly changed the long-standing advice about passing function arguments by reference. Namely, if we are using a const reference only to copy the object for local usage, as discussed previously in this chapter, then we create a temporary and then copy out its contents. If we have a movable object, this is a waste of time, and we might want to define an overload taking a movable reference. A small optimization in code size is to pass the object by value, hence sparing one of the overloads:

// two overloads
func(const T& t);
func(T&& t);

// replaced with one:
func(T t);

The replacement function will, in the case of a const reference, perform one copy and one move and, in the case of an rvalue reference, it performs two moves, hence only paying the price of one extra move compared to the case of two separate overloads (check it!). So, it is OK if the moves are cheap, which they are supposed to be.