Why doesn’t C++ move construct rvalue references by default? [duplicate]

with your design: void doWork(Widget && param) { Widget store1 = param; // automatically move param Widget store2 = param; // boom Widget store_last = param; // boom } with current design: void doWork(Widget && param) { Widget store1 = param; // ok, copy Widget store2 = param; // ok, copy Widget store_last = std::move(param); … Read more

How to make template rvalue reference parameter ONLY bind to rvalue reference?

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

Can I typically/always use std::forward instead of std::move?

The two are very different and complementary tools. std::move deduces the argument and unconditionally creates an rvalue expression. This makes sense to apply to an actual object or variable. std::forward takes a mandatory template argument (you must specify this!) and magically creates an lvalue or an rvalue expression depending on what the type was (by … Read more