可能重複:
Why copy constructor is not called in this case?複製構造函數沒有調用,爲什麼?
我有以下代碼:
#include <iostream>
#include <new>
using namespace std;
class test {
int *p;
public:
test operator=(test a);
test() {
p = new int [2];
cout <<"Default Constructor was done here." << "\n";
}
test(const test &a) {
p = new int [2];
this->p[0] = a.p[0];
this->p[1] = a.p[1];
cout << "Copy Constructor was done here." << "\n";
}
~test() {
delete p;
cout << "Destructor was done here." << "\n";
}
int set (int a, int b) {
p[0] = a;
p[1] = b;
return 1;
}
int show() {
cout << p[0] << " " << p[1] << "\n";
return 2;
}
};
test test::operator=(test a) {
p[0] = a.p[0];
p[1] = a.p[1];
cout << "Operator = was done here" << "\n";
return *this;
}
test f(test x) {
x.set(100, 100);
return x;
}
int main() {
test first;
test second;
first.set(12, 12);
//f(first);
//second = first;
second = f(first);
first.show();
second.show();
getchar();
return 0;
}
拷貝構造函數被調用只有三次?爲什麼? 如果我理解,我們做了四個副本(我們發送對象到func,func返回值,我們發送對象給operator =,operator =返回值)。
複製elision,大量重複... –