#fowarding reference

1 messages · Page 1 of 1 (latest)

crimson quiver
#

hi all, can anyone give me some examples where std::forward is useful? It seems the function will return lvalue or rvalue depending on what we passed in, but I dont see why we really need it, we can just pass it directly and resolve them through function overloading?

strange sirenBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question run !howto ask.

nova robin
#

that is use for template functions. cuz a template class argument with"&&" can not only accept rvalue but also lvalue, so we need to use std::forward to return its original atrribution if we wanna call overload functions that distinguish by rvalue or lvalue, for example move constructor or copy constructor.

uncut oasis
#

for example std::make_unique<T> takes a pack of forwarding references which is passed to the constructor of T

#

you can't really make an overload for every possible combination of lvalue and rvalue references due to the nature of this being a variadic function

#

and you need std::forward for forwarding references because when accessed, they all turn into lvalues by default

#

you wouldn't get any move semantics without it

grave ginkgo
#

Basically it is used to solve the equivalence problem. If you have a function that calls another function, the inner function will see every parameter as lvalues. This causes problems when you are trying to make the inner function call a move constructor, for example, because you need rvalues to do that. std::forward works by maintaining the value category of a parameter so that problem doesn't happen.

crimson quiver
#

wait, so using function parameters inside the function will be treated as lvalues ?

uncut oasis
trail willow
#

if it has a name, it's an lvalue

uncut oasis
trail willow
#

well, calls to functions that return references, yes ^^

uncut oasis
#

concepts also kinda break the mold

trail willow
signal hemlock
#

yooooooo when did you guys refactor the design of #1124619767542718524 ? It looks so pretty with separate threads 🥰