C++ 使用复制和流迭代器将对象直接读入向量时的复制构造函数问题
在运行以下代码时,请解释输出中的行为。 我不太清楚复制构造函数被调用的次数C++ 使用复制和流迭代器将对象直接读入向量时的复制构造函数问题,c++,stl,iterator,C++,Stl,Iterator,在运行以下代码时,请解释输出中的行为。 我不太清楚复制构造函数被调用的次数 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;
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;
}
我认为在插入向量时,复制构造函数会被调用一次,因为容器按值存储对象。复制构造函数至少应该被调用3次:
- 每个传递给
的istream_迭代器1份副本,如下所示std::copy
存储本地 参数化类型的值和 很可能是在副本中复制的 构造函数,它们被传递 值设置为istream\u迭代器
。(二)std::copy
- 1插入到
向量中
EDIT2:当我用VS2008运行这个时,我得到了对复制构造函数的7个调用。另外4个是围绕输入迭代器复制到
以在调试构建中进行边界检查的结果。在完全优化的构建中运行时,我只收到3次对复制构造函数的调用。istream\u迭代器正在构建并复制了很多次。以下是我的输出:std::copy
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
你试过打开优化吗?即使使用3级优化,我也没有收到相同数量的复制构造函数调用,我使用的是gcc版本4.4.3。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