返回临时,为什么不参考
Returning temporary, why not a rvalue reference?
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;
}
相关文章:
- 为什么不;名字在地图上是按顺序排列的吗
- 为什么不能修改对象中的值?另外,我如何改进此链表?
- 为什么不调用移动构造函数?(默认情况下只有构造器,没有别的)
- C++ 基本 CTOR 说明 - 为什么不调用赋值/复制构造函数
- 为什么不递增?(构造函数)
- 为什么不允许成员函数和非成员函数之间的函数重载?
- 为什么不允许使用可变长度数组作为向量元素?
- C++:为什么不调用移动构造函数?
- 在 C++ 中声明 const 对象需要用户定义的默认构造函数.如果我有一个可变成员变量,为什么不呢?
- 为什么不能用常量表达式声明数组?
- 为什么不能直接引用作用域枚举类成员,而不能为无作用域枚举生成类成员?
- C++ queue.front();为什么不从第一个元素开始呢?
- 为什么不允许这种交叉广播?
- 通过构造函数方法输出的类到类类型转换是 5500 为什么不是 5555
- 为什么不能通过在错误输入后设置 std::cin.clear() 来使用 std::cin?
- 为什么不支持 Xcode 1.5?
- C 参考class对象的返回 - 为什么不工作
- 返回临时,为什么不参考
- int &a = b 使 'a' 成为 C 4.8.1 中指向 'b' 的指针,但在 C 中不是,为什么?(参考电话)
- 右值参考:为什么不隐式移动右值?