我正在尝试测试RVO和右值参考。这是代码:
#include <iostream>
using namespace std;
class B{
public:
int i;
B(){
i = 0;
cout << "B() " << i << endl;
}
B(const B& b){
i = 1;
cout << "B(const B&) " << i << endl;
}
B(const B&& b){//if remove this constructor, then call B(const B& b)
i = 2;
cout << "B(const B&&) " << i << endl;
}
~B(){
cout << "~B() " << i << endl;
}
};
B f(){
B b;
return b;
}
int main(){
B b = f();
return 0;
}
输出是:
B() 0
B(const B&&) 2
~B() 0
~B() 2
环境:WIN8,Visual Studio 2012 Express
这意味着调用了移动构造函数:B(const B&&)。提出了两个问题:
- 为什么这里不应用RVO ?
- 为什么不调用复制构造函数: B(const B&)?
如果我删除B(const B&&),则调用B(const B&) 。奇怪的输出:
B() 0
B(常量 B&) 1
~B() 0
~B() 1
以下是我找到的参考资料:
- 为什么 g++ 在这里不启用 RVO?
- RVO, move operations and a dilemma 但是,它们的场景与我的不同(RVO因功能参数而失败)。
编辑:移动构造函数
应该是B(B&&)。问题是为什么调用构造函数而不是复制构造函数。