H X*_* Xu 1 c++ rvalue-reference c++11
我正在玩这个例子来理解右值引用:
#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
}
Run Code Online (Sandbox Code Playgroud)
我很难理解为什么在行v.push_back(Dog())中,对象Dog()被视为Rvalue(因此调用移动构造函数),但以下两行不会调用移动构造函数.我想我可能会误解匿名对象和RValue之间的关系.
这是因为返回值优化.您的编译器非常智能,可以看到最后两行可以简化为:
Dog c;
Dog d;
Run Code Online (Sandbox Code Playgroud)
因此,只允许将代码重写为上面的代码.由于push_back不符合允许RVO的要求,因此创建临时数据并在您目睹时简单地移动.尝试将打印添加到构造函数中,它会变得更清晰.
| 归档时间: |
|
| 查看次数: |
111 次 |
| 最近记录: |