c++的浅复制与深复制

来源:互联网 发布:最基本的网络拓扑结构 编辑:程序博客网 时间:2024/05/17 13:39

class CDemo
{
        public:
                CDemo():str(NULL){printf("cdemo()\n");}
                ~CDemo()
                {
                        if(str)
                        {
                                static int i =0;
                                cout<<"&CDemo="<<i++<<" = "<<(int*)this << " ,str = "<<(int*)str<<endl;
                                delete str;
                        }
                }

               //复制构造函数
                CDemo(const CDemo &cd)
                {
                        printf("&cd\n");
                        this->str = new char[strlen(cd.str)+1];
                        strcpy(str,cd.str);
                }
        char *str;
};

void test47()
{
        CDemo d1;
        d1.str=new char[22];
        strcpy(d1.str,"hello world");

        vector<CDemo> *a1 = new vector<CDemo>();
        a1->push_back(d1);

        vector<CDemo>::iterator p = a1->begin();
        printf("p->str=%s\n",p->str);
        printf("d1.str=%s\n",d1.str);
        delete a1;
        printf("p->str=%s\n",p->str);
        printf("d1.str=%s\n",d1.str);
}

0 0
原创粉丝点击