简体   繁体   中英

C++ Perfect forwarding vs const reference

Ok guys I have a simple question I do not understand

int solution(int&& a, int&& b);

int main() {
    int a, b;
    std::cin >> a >> b;
    std::cout << solution(std::forward<int>(a), std::forward<int>(b)) << std::endl;
}

int solution(int&& a, int&& b) {
    return a + b;
}

I am a Java developer and started to re-learn C++ from my University background level and I always see "&&" after the any type, I've learnt that that is a rvalue reference, then I've learnt about move constructors etc... I just do not understand clearly what does std::forward do beyond the scenes? Does it really give the rvalue reference so no copy of argument is created? If that is right why is it better than writing just const int&?(I do not copy anything here either... The question may be silly, but thanks in advance)

Does it really give the rvalue reference so no copy of argument is created?

Yes.

If that is right why is it better than writing just const int&?(I do not copy anything here either.

It isn't.

In fact, for a simple int , you shouldn't even be passing by reference. They're small enough that a nice simple pass-by-copy is preferable (and, oddly, perhaps easier to optimise).

Rvalue references are useful for implementing move semantics (with classes that have indirect resources that can be transferred) and perfect forwarding, not for simple non-mutating function arguments.

Your example has nothing to do with perfect forwarding; it's just passing a reference to a function.

I always see "&&" after the any type

You shouldn't see it "always".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM