有些正文可以在运行以下代码时解释输出中的行为。 我对复制构造函数被调用的次数感到困惑。
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$
我认为复制构造函数在插入向量时会被调用一次,因为容器按值存储对象。
答案 0 :(得分:0)
复制构造函数应至少调用3次:
istream_iterator
个副本传递给std::copy
,如
istream_iterator
存储本地
参数化类型的值和
最有可能将其复制到副本中
构造函数,他们通过
价值为std::copy
。 (2)vector<A> vA
通过vA.push_back(...)
插入back_inserter(vA)
std::copy
作业
运营商。 (3)编译器可能会优化其中的一些副本,但其他8个副本来自我是个谜。
编辑:顺便提一下,我在codepad.org上运行了8次调用复制构造函数:http://codepad.org/THFGFCCk
EDIT2:当我用VS2008运行时,我有7次调用复制构造函数。另外4个是将输入迭代器复制到{{1}}以便在调试版本中进行边界检查的结果。在完全优化的构建中运行时,我只能对复制构造函数进行3次调用。
答案 1 :(得分:0)
istream_iterator正在构建和复制很多次。这是我的输出:
40
copy constructor invoked
copy constructor invoked
copy constructor invoked
copy constructor invoked
destructor called
destructor called
destructor called
destructor called
copy constructor invoked
copy constructor invoked
destructor called
copy constructor invoked
copy constructor invoked
destructor called
copy constructor invoked
copy constructor invoked
copy constructor invoked
copy constructor invoked
copy constructor invoked
copy constructor invoked
copy constructor invoked