何时引用为右值引用

When is a reference an Rvalue reference?

本文关键字:引用 何时      更新时间:2023-10-16

我正在玩这个例子来理解右值引用:

#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的要求,因此创建了临时的,并且像您所看到的那样简单地移动了。尝试将打印添加到构造函数,它会变得更清晰。