对下面的一段代码的输出看不懂,求解释下#include <iostream>
#include<vector>
#include<deque>
#include<list>
#include<string>using namespace std;
class test{
public:
int a;
int *b;
test(int a){
this->a=a;
b=new int[5];
b[0]=11;
b[1]=12;
cout<<"construct a="<<a<<endl;
}
test(const test & t){
a=t.a+1;
b=new int[5];
cout<<"copy construct"<<"a="<<a<<endl;
}
~test(){
delete[]b;
cout<<"deconstruct"<<"a="<<a<<endl;
}};
int main(int argc,char**argv){
vector<test> te;
test aa(1);
te.push_back(aa);
cout<<"---"<<endl;
te.push_back(aa);
//te.push_back(a);
char tmp;
cin >>tmp;
return 0;
}C c++  复制构造函数 

解决方案 »

  1.   

    test aa(1);调用构造函数
    te.push_back(aa);调用拷贝构造函数
    函数退出时调用析构函数啊输出是什么样的啊?
      

  2.   

    ---下面为什么不是copy constructa=2
      

  3.   

    你不是
    a=t.a+1;
    每拷贝一次a增加1,所以完全正确。
      

  4.   

    ---下面为什么不是copy constructa=2 
      

  5.   

            test(const test & t){           
                    a=t.a+1;           
                   b=new int[5];            
                 cout<<"copy construct"<<"a="<<a<<endl;            
    }
    我认为如果输出a=3那么t.a==2,那么te.push_back(aa);中的aa.a==2 ,但是复制构造函数是常引用啊不会改变aa.a的值吧,能解释下么?
      

  6.   

    好久前自己的帖子,现在看,一眼看明白,原因是vector的reserve和capacity机制,插入第一个元素时,vector为空,这时分配空间,然后直接拷贝所以 “construct a=1 和copy constructa=2",插入第二个元素时,没有足够的空间了,所以需要重新分配,然后将原来的那个元素拷贝到新空间,所以copy constructa=3,然后释放旧空间,deconstructa=2,最后插入新元素,copy constructa=2