How can I make a forwarding-reference parameter bind only to rvalue references?

You can restrict T to not be an lvalue reference, and thus prevent lvalues from binding to it: #include <type_traits> struct OwnershipReceiver { template <typename T, class = typename std::enable_if < !std::is_lvalue_reference<T>::value >::type > void receive_ownership(T&& t) { // taking file descriptor of t, and clear t } }; It might also be a good … Read more

Is it necessary to std::move in a return statement, and should you return rvalue references?

First example std::vector<int> return_vector(void) { std::vector<int> tmp {1,2,3,4,5}; return tmp; } std::vector<int> &&rval_ref = return_vector(); The first example returns a temporary which is caught by rval_ref. That temporary will have its life extended beyond the rval_ref definition and you can use it as if you had caught it by value. This is very similar to … Read more

Forwarding of return values. Is std::forward is needed?

In the case that you do know that t will not be in a moved-from state after the call to f, your two somewhat sensible options are: return std::forward<T>(t) with type T&&, which avoids any construction but allows for writing e.g. auto&& ref = wrapper(42);, which leaves ref a dangling reference return std::forward<T>(t) with type … Read more

Differences between std::is_convertible and std::convertible_to (in practice)?

std::is_convertible<From, To> (the type trait) checks is type From is implicitly convertible to type To. std::convertible_to<From, To> (the concept) checks that From is both implicitly and explicitly convertible to To. It’s rare that this is not the case, such types are ridiculous, but it’s nice in generic code to just not have to worry about … Read more

Is the pass-by-value-and-then-move construct a bad idiom?

Expensive-to-move types are rare in modern C++ usage. If you are concerned about the cost of the move, write both overloads: void set_a(const A& a) { _a = a; } void set_a(A&& a) { _a = std::move(a); } or a perfect-forwarding setter: template <typename T> void set_a(T&& a) { _a = std::forward<T>(a); } that will … Read more

tech