我已经尝试过我的代码以了解其copy constructor工作原理。这是我的代码:
#include <iostream>
using namespace std;
class B{
public:
B(){
cout << "B()\n";
}
B(const B& b){
cout << "B(const B&)\n";
}
~B(){
cout << "~B()\n";
}
};
int main(){
B b = B();
return 0;
}
对于代码B b = B(),我认为流程是这样的:
- 调用构造函数
B(),打印B(),返回一个临时对象类型B; - 调用复制构造函数
B(const B&),将步骤 1 中返回的对象作为参数传递,打印B(const B&),初始化变量b。
但是我的代码只是输出B(),这意味着没有copy constructor被调用。问题是什么?