---restore content starts---
Original:bit copy and value copy in C + +
Original: http://blog.csdn.net/liam1122/article/details/1966617
For illustrative purposes we take the string class as an example:
The string class is defined first, and its member functions are not implemented.
Class string{public : string (const char *ch=null);//default constructor string (const string &str);//copy Constructor ~ String (void); String &operator= (const string &str);//Assignment Function private: char *m_data;};
A bit copy is an address, while a value copy copies the contents. If you define two string objects A and B. A.m_data and B.m_data respectively point to a section of the area, a.m_data= "Windows", B.m_data= "Linux";
If the assignment function is not overridden, assigning B to A; the compiler defaults to a bit copy, A.m_data=b.m_data
The A.m_data and B.m_data point to the same area, although the A.m_data point is changed to "Linux", but these problems are easily seen:
(1): A.m_data The memory area originally pointed to is not released, causing a memory leak.
(2): A.m_data and B.m_data point to the same area, any change will affect the other party
(3): B.m_data is released two times when the object is being refactored.
For compilers, if you do not actively write copy functions and assignment functions, it will automatically generate default functions in a "bit copy" manner.
If you override the assignment function and the copy constructor,
A.m_data=b.m_data, which is a value copy, assigns the contents of the B.m_data to A.m_data,a.m_data or to the original memory area, but its contents change.
A bit copy is an address, while a value copy copies the contents.
A bit copy is the address of a parameter that is passed, and a value copy is the value of the parameter itself.
A deep copy is an object, and a shallow copy of the copy is memory.
A bitwise copy is a copy of the object, which is actually used to copy the data to the destination object, such as memcpy (), and copies each member of the class by the member copy (these members may want to invoke their own defined copy function). This will be slow. Bit copies are fast. But semantically not always what we want. So they are each of their own use.
Reference:
http://topic.csdn.net/u/20081106/12/4ac743c8-99a2-4dd9-8532-3378e644a0f8.html?85412
---restore content ends---
Reprint bit copy and value copy in C + +