gpt4 book ai didi

c++ - 如何计算将对象插入 vector 时使用复制构造函数的次数?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:21:41 24 4
gpt4 key购买 nike

<分区>

当把两个元素压入vector时,我想应该是用了两次copy operator。当对象解构时使用析构函数。但是结果显示,它使用了三次拷贝构造函数,并在压入对象后立即使用了一次析构函数。那么这个问题的原因是什么?

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;
}

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com