夏天/isummer

Sun of my life !Talk is cheap, Show me the code! 追风赶月莫停留,平芜尽处是春山~

博客园 首页 新随笔 联系 管理

STL中list中push_back(对象)保存对象的内部实现

1. 在容器中,存放的是对象拷贝

  

#include<iostream>
#include<list>
using namespace std;

class A{
    int i;
    static int num;
public:
    A():i(0){ cout<<"A()" <<endl; num ++;}
    A(int ii):i(ii){ cout<<"A(int)" <<endl; num ++;}
    ~A(){ cout<< "~A" <<endl;}
    A(const A& a){
        i = a.i;
        cout<<"A(const A&)"<<endl;
        num ++;
    }
    A& operator =(const A& a){
        cout<<"operator="<<endl;
        i = a.i;
        return *this;

    }
    void print(){
        cout<<i<<endl;
    }
    void printN(){
        cout<< " num = "<<num<<endl;
    }
};

int A::num = 0;

int main(){
    //A a(1);
    //A b = a;
    //A c;
    //c = a;
    //c.print();
    //a.printN();
    list<A> li;
    li.push_back(A(2));
    list<A>::iterator it = li.begin();
    (*it).printN();
}

输出结果:
A(int)//A2临时对象
A(
const A&)//li.push_back(A(2))调用其复制构造函数 ~A//离开临时对象作用域A调用其析构函数 num = 2 ~A //程序结束 从输出结果可以看出传到list中的是对象的拷贝。

 

posted on 2015-12-17 17:48  夏天/isummer  阅读(2948)  评论(0编辑  收藏  举报