C + +, a copy constructor is generated by default, and when a pointer appears in a class, the copy performs a shallow copy, that is, only the address of the pointer is copied, and the data is not copied;
So in class, when using pointers, you need to be aware of; If you want to use a deep copy, you can add a copy constructor.
The following code, if you do not add a copy constructor, will run an error, but you can compile,
At runtime, the program cannot execute because deletion (delete[]) is two times the same address space as Str refers to.
Code:
* * * main.cpp * * Created on:2014.4.15 * author:spike//*vs2012*/#include <iostream
> #include <cstring> #include <vector> #include <memory> using namespace std;
Class CDemo {Public:cdemo (): Str (NULL) {};
~cdemo () {static int i=0; if (str) {std::cout << "&demo" << i++ << "=" << (int*) this <<, str =
"<< (int*) str << Std::endl;
Delete[] STR;
}///copy constructor CDemo (const cdemo& CD) {this->str = new Char[strlen (CD.STR) + 1];
strcpy (This->str, CD.STR);
} char* str;
};
int main () {CDemo D1;
D1.STR = new CHAR[32];
strcpy (D1.str, "Caroline");
std::vector<cdemo>* A1 = new std::vector<cdemo> (); A1->push_back (D1); Perform a copy constructor std::cout << "D1.str =" << d1.str << Std::endl;
Std::cout << "(*a1) [0].STR =" << (*A1) [0].str << Std::endl;
strcpy (D1.str, "Wendy");
Std::cout << "d1.str =" << d1.str << Std::endl;
Std::cout << "(*a1) [0].STR =" << (*A1) [0].str << Std::endl;
Delete A1;
return 0; }
Output:
D1.str = Caroline
(*a1) [0].str = Caroline d1.str
= Wendy
(*A1) [0].str = Wendy
&demo0 = 0x312570, str = 0x312548
&demo1 = 0x22fec8, str = 0x312548
Author: csdn Blog spike_king
More Wonderful content: http://www.bianceng.cnhttp://www.bianceng.cn/Programming/cplus/