返回临时,为什么不参考

Returning temporary, why not a rvalue reference?

本文关键字:为什么不 参考 返回      更新时间:2023-10-16

rvalue参考是临时对象吗?为什么不进行以下编译?我认为此功能返回了RVALUE参考

main.cpp:40:12: error: no viable conversion from 'hello3 ()' to 'hello4'
    hello4 lol = returning;

在代码中

#include <iostream>
#include <string>
#include <vector>
class hello {
  public:  
};

class hello2 {
  public:  
};
class hello3 {
  public:  
  hello obj1;
  hello2 obj2;
};

class hello4 {
 public:
 hello4(hello3&&) {
  std::cout << "he";   
 }
};
hello3 returning() {
    hello a;
    hello2 b;
    return {a,b};
}
int main()
{
    hello4 lol = returning;
}

我阅读了移动语义文档,但我仍然不明白为什么以上内容不绑定到rvalue参考

rvalue参考是临时对象吗?

否,这是对可能不是临时的对象的引用。

为什么不进行以下编译?

因为您将(空)参数列表列出了函数调用:

hello4 lol = returning();
                      ^^

错误消息指示您的代码试图分配一个函数,而不是调用函数的结果。

我认为此功能返回了RVALUE参考

否,它返回一个对象,这也一样,因为没有任何参考。但是该临时对象可以绑定到 rvalue 参考,因此可以用于构造hello4

上面的编译器错误与对象是什么样式:

hello4 lol = returning;

应该是

hello4 lol = returning();

没有括号,编译器认为您正在尝试将函数分配给hello4值。您可以在这里看到此内容:

int main()
{
    auto lol = returning;
    hello4 foo = lol();
    return 0;
}