【发布时间】:2010-11-20 08:40:54
【问题描述】:
在运行以下代码时,请一些人解释输出中的行为。 我对复制构造函数被调用的次数有点困惑。
using namespace std;
class A {
int i;
public:
A() {
};
A(const A& a) {
i = a.i;
cout << "copy constructor invoked" << endl;
};
A(int num) {
i = num;
};
A& operator = (const A&a) {
i = a.i;
// cout << "assignment operator invoked" << endl;
};
~A() {
cout << "destructor called" << endl;
};
friend ostream& operator << (ostream & out, const A& a);
friend istream& operator >> (istream &in, A&a);
};
ostream & operator << (ostream &out, const A& a) {
out << a.i;
return out;
}
istream & operator >> (istream & in, A&a) {
in >> a.i;
return in;
}
int main() {
vector<A> vA;
copy(istream_iterator<A>(cin), istream_iterator<A>(), back_inserter(vA));
// copy(vA.begin(), vA.end(), ostream_iterator<A>(cout, "\t"));
return 0;
}
观察到的输出是
ajay@ubuntu:~/workspace/ostream_iterator/src$ ./a.out
40
copy constructor invoked
copy constructor invoked
copy constructor invoked
copy constructor invoked
copy constructor invoked
copy constructor invoked
copy constructor invoked
copy constructor invoked
copy constructor invoked
copy constructor invoked
copy constructor invoked
destructor called
destructor called
destructor called
destructor called
destructor called
destructor called
destructor called
destructor called
destructor called
destructor called
destructor called
destructor called
destructor called
ajay@ubuntu:~/workspace/ostream_iterator/src$
我认为复制构造函数在插入向量时会被调用一次,因为容器按值存储对象。
【问题讨论】:
-
你试过开启优化吗?
-
即使使用 3 级优化,我也得到相同的复制构造调用次数,并且我使用的是 gcc 版本 4.4.3。