参考如下文章:
拷贝构造函数什么时候调用?
补充:
当一个函数中形参和返回值都是对象,理论上应该调用两次拷贝构造函数,但是实际上只调用了一次。编译器为了提高效率把这两次合并了。
如:
#include<iostream>
#include<string>
#include<vector>
using namespace std;
class B{
private:
int data;
public:
B(){
cout << "default constructor" << endl;
}
B(const B &other){
cout << "kaobei" << endl;
}
~B(){
cout << "destructed" << endl;
}
B(int i) :data(i){
cout << "constructed by parameter" << data << endl;
}
};
B Play(B b){//函数中形参和返回值都是对象
return b;
}
int main(){
B temp = Play(5);
return 0;
}
//输出结果:
constructed by parameter5
kaobei
destructed
destructed