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

Capturing perfectly-forwarded variable in lambda

Is it correct to capture the perfectly-forwarded mStuff variable with the &mStuff syntax? Yes, assuming that you don’t use this lambda outside doSomething. Your code captures mStuff per reference and will correctly forward it inside the lambda. For mStuff being a parameter pack it suffices to use a simple-capture with a pack-expansion: template <typename… T> … Read more

Perfect forwarding – what’s it all about? [duplicate] Why is this useful? Well, it means that a function template can pass its arguments through to another function whilst retaining the lvalue/rvalue nature of the function arguments by using std::forward. This is called “perfect forwarding”, avoids excessive copying, and avoids the template author having to write multiple overloads for lvalue and rvalue references.

Is there a difference between universal references and forwarding references?

Do they mean the same thing? Universal reference was a term Scott Meyers coined to describe the concept of taking an rvalue reference to a cv-unqualified template parameter, which can then be deduced as either a value or an lvalue reference. At the time the C++ standard didn’t have a special term for this, which … Read more

What does T&& (double ampersand) mean in C++11?

It declares an rvalue reference (standards proposal doc). Here’s an introduction to rvalue references. Here’s a fantastic in-depth look at rvalue references by one of Microsoft’s standard library developers. CAUTION: the linked article on MSDN (“Rvalue References: C++0x Features in VC10, Part 2”) is a very clear introduction to Rvalue references, but makes statements about … Read more

Perfect forwaring of auto&& in generic lambda

In C++20 and later auto lambda20 = []<class F, class…Ts>(F &&fn, Ts &&…args) { return std::forward<F>(fn)(std::forward<Ts>(args)…); }; In C++pre20 : C++11,14,17 auto lambda14 = [](auto &&fn, auto &&…args) { return std::forward< std::conditional_t< std::is_rvalue_reference_v<decltype(fn)>, typename std::remove_reference_t<decltype(fn)>, decltype(fn)> >(fn)( std::forward< std::conditional_t<std::is_rvalue_reference<decltype(args)>::value, typename std::remove_reference<decltype(args)>::type, decltype(args) >>(args)…); }; Example #include <iostream> using namespace std; int main() { auto lambda20 … Read more