何时引用为右值引用
When is a reference an Rvalue reference?
我正在玩这个例子来理解右值引用:
#include <string>
#include <iostream>
#include <utility>
#include <vector>
class Dog
{
public:
Dog() {};
Dog(Dog&& a) { std::cout << "R value" << std::endl;}
};
Dog foo()
{
return Dog();
}
int main()
{
std::vector<Dog> v;
v.push_back(Dog()); // calls move constructor
Dog c((Dog())); // does not call move constructor
Dog d(foo()); // does not call move constructor
}
我很难理解为什么在第 v.push_back(Dog((( 行中,对象 Dog(( 被视为 Rvalue(因此调用了移动构造函数(,但以下两行不调用移动构造函数。我想我可能误解了匿名对象和RValue之间的关系。
这是因为返回值优化。您的编译器足够聪明,可以看到最后 2 行可以简化为:
Dog c;
Dog d;
因此,允许将代码重写为上面的代码。由于push_back
不符合允许RVO的要求,因此创建了临时的,并且像您所看到的那样简单地移动了。尝试将打印添加到构造函数,它会变得更清晰。
相关文章:
- 何时在引用或唯一指针上使用移动语义
- 何时应通过引用传递矢量参数而不是按值传递矢量参数?
- 如果非动态变量被指针引用,何时超出范围?
- 何时使用右值引用
- C++ 何时使用常量引用而不是转发引用
- 了解shared_ptr传入函数时引用计数何时递增
- C++ / Qt:如何检测主机名或IP地址何时引用当前系统?
- 常量引用函数参数的地址何时唯一?
- 返回的常量引用究竟何时被销毁
- 何时引用为右值引用
- 何时应存储指向函数的引用或指针?
- 引用变量何时合适,为什么?你能解释一下实际的语法和位置吗?
- 何时首选常量左值引用而不是右值引用模板
- c++中重载运算符何时通过引用传递
- 何时将类的引用分配给其父类的 instace
- 引用对象的动态类型何时可以更改
- 何时通过引用 C++ 中的函数来传递和返回
- 引用参数何时可以接受 int 文本
- 如果未在本机方法中创建,何时清除本地引用
- 何时解析 C++11 lambda 表达式中的变量引用