简体   繁体   English

C++ 完美转发 vs const 引用

[英]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?我是一名 Java 开发人员,从我的大学背景水平开始重新学习 C++,我总是在 any 类型后面看到“&&”,我了解到这是一个右值引用,然后我了解了移动构造函数等。 .. 我只是不明白 std::forward 在场景之外做了什么? 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)如果这是对的,为什么比只写 const int& 更好?(我也不在这里复制任何东西......这个问题可能很愚蠢,但提前致谢)

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.如果这是对的,为什么比只写 const int& 更好?(我也不在这里复制任何内容。

It isn't.不是。

In fact, for a simple int , you shouldn't even be passing by reference.事实上,对于一个简单的int ,你甚至不应该通过引用传递。 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".你不应该“总是”看到它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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