How does std::forward work, especially when passing lvalue/rvalue references? [duplicate]

I think the explanation of std::forward as static_cast<T&&> is confusing. Our intuition for a cast is that it converts a type to some other type — in this case it would be a conversion to an rvalue reference. It’s not! So we are explaining one mysterious thing using another mysterious thing. This particular cast is …

Read more

Should all/most setter functions in C++11 be written as function templates accepting universal references?

You know the classes A and B, so you know if they are movable or not and if this design is ultimately necessary. For something like std::string, it’s a waste of time changing the existing code unless you know you have a performance problem here. If you’re dealing with auto_ptr, then it’s time to rip …

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

Perfect forwarding – what’s it all about? [duplicate]

http://www.justsoftwaresolutions.co.uk/cplusplus/rvalue_references_and_perfect_forwarding.html 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

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