c++的浅复制与深复制

xiaoxiao2021-02-28  124

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); }

转载请注明原文地址: https://www.6miu.com/read-50296.html

最新回复(0)