is there a difference between move and forward here:
void test(int && val)
{
val=4;
}
void main()
{
int nb;
test(std::forward<int>(nb));
test(std::move(nb));
std::cin.ignore();
}
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
In your specific case, no, there isn’t any difference.
Detailed answer:
Under the hood,
std::move(t)doesstatic_cast<typename std::remove_reference<T>::type&&>(t), whereTis type oft(see §20.2.3/6). In your case, it resolves tostatic_cast<int&&>(nb).forwardis a little bit tricky, because it is tailored for use in templates (to allow perfect forwarding) and not as a tool to cast lvalue to rvalue reference.Standard library provides two overloads (one for lvalue references and the second for rvalue ones, see §20.2.3/2):
Substituting
int, we get:And since
nbis lvalue, the first version is chosen. According to standard draft, the only effect offorwardisstatic_cast<T&&>(t). WithTbeingint, we getstatic_cast<int&&>(nb), i.e. – we get two exactly same casts.Now, if you want to cast lvalue to rvalue (to allow moving), please use only
std::move, which is the idiomatic way to do this conversion.std::forwardis not intended to be used this way.