【发布时间】:2019-03-25 12:15:59
【问题描述】:
将两个元素推入向量时,我认为应该使用两次复制运算符。当对象解构时使用析构函数。但是,结果显示它使用了 3 次复制构造函数,并在推送对象后立即使用了一次析构函数。那么这个问题的原因是什么?
using namespace std;
struct X {
X() { cout << "X()" << endl; }
X(const X&) { cout << "X(const X&)" << endl; }
X& operator=(const X& xr) { cout << "operator=(const X& xr)" << endl; return *this; }
~X() { cout << "~X()" << endl; }
};
void fcn1(X x1, X &x2, X *x3) {
cout << "fcn1 start" << endl;
vector<X> v1;
cout<<"push x"<<endl;
v1.push_back(x1);
v1.push_back(x2);
cout << "fcn1 end" << endl;
}
【问题讨论】:
标签: c++ copy-constructor