jeudi 22 septembre 2016

Constructor using std::forward

To my knowledge, the two common ways of efficiently implementing a constructor in C++11 are using two of them

Foo(const Bar& bar) : bar_{bar} {};
Foo(Bar&& bar)      : bar_{std::move(bar)} {};

or just one in the fashion of

Foo(Bar bar) : bar_{std::move(bar)} {};

with the first option resulting in optimal performance (e.g. hopefully a single copy in case of an lvalue and a single move in case of an rvalue), but needing 2N overloads for N variables, whereas the second option only needs one function at the cost of an additional move when passing in an lvalue.

This shouldn't make too much of an impact in most cases, but surely neither choice is optimal. However one could also do the following:

template<typename T>
Foo(T&& bar) : bar_{std::forward<T>(bar)} {};

This has the disadvantage of allowing variables of possibly unwanted types as the bar parameter (which is a problem I'm sure is easily resolved using template specialization), but in any case performance is optimal and the code grows linearly with the amount of variables.

Why is nobody using something like forward for this purpose? Isn't it the most optimal way?

Aucun commentaire:

Enregistrer un commentaire