Copy constructors and value assignment functions

Source: Internet
Author: User
Value assignment function Each class has only one value assignment function.Since not all objects use copy constructor and value assignment function, programmers may despise these two functions. Remember the following warning first, and read the text with caution: 1.If you do not write the copy constructor and value assignment function, the compiler automatically generates the default function in the "bit copy" mode. If the class contains pointer variables, the two default functions are implicitly incorrect. Take the two objects A and B in the string type as an example. Assume that the content of A. m_data is "hello", and the content of B. m_data is "world ". Now assign A to B. The "bit copy" of the default value assignment function means that B. m_data = A. m_data is executed. This will cause three errors: B. m_data memory is not released, causing memory leakage; B. m_data and. m_data points to the same memory. Changes to either of A or B will affect the other. Third, m_data is released twice when the object is destructed. 2.The copy constructor and the value assignment function are very confusing and often lead to incorrect writing and usage. A copy constructor is called when an object is created, and a value assignment function can only be called by an existing object. In the following program, the third statement is very similar to the fourth statement. Do you know which one calls the copy constructor and which one calls the value assignment function? String A ("hello"); string B ("world"); string c = A; // call the copy constructor. It is best to write it as C (a); C = B; // The Value assignment function is called. In this example, the third statement has a poor style and should be rewritten to string C (A) to distinguish it from the fourth statement. String-like copy constructor and value assignment function //
Copy constructor string: string (const string & Other) {// Private member m_dataint length = strlen (Other. m_data); m_data = new char [Length + 1]; strcpy (m_data, other. m_data) ;}// value assignment function string & string: Operator = (const string & Other) {// (1) Check auto-assigned if (this = & other) return * This; // (2) release the original memory resource Delete [] m_data; // (3) allocate new memory resources and copy the content int length = strlen (Other. m_data); m_data = new char [Length + 1]; strcpy (m_data, other. m_dat A); // (4) return the reference return * This;} the difference between the class string copy constructor and the common constructor is that there is no need to compare it with null at the function entrance, this is because "Reference" cannot be null, and "Pointer" can be null. The value assignment function of the string type is much more complex than the constructor. It is implemented in four steps: (1) The first step is to check the self-assignment. You may think that, in this case, someone will be stupid enough to write an auto-assigned statement like a =! No. However, indirect auto-assigned values may still appear. For example, the content auto-assigned value B = ;... C = B ;... A = C; // address self-assigned B = & ;... A = * B; some people may say, "even if there is a self-assigned value, I can ignore it. If it is a big deal, let the object copy itself. It will not make any mistakes !" He is really wrong. Check the delete in step 2. Can I copy myself after suicide? Therefore, if the auto-assigned value is found, the function should be terminated immediately. Do not mistakenly write the IF (this = & Other) statement that checks the self-assigned values into if (* This = Other) (2) Step 2, use Delete to release original memory resources. If it is not released now, there will be no chance in the future, which will cause memory leakage. (3) Step 3: allocate new memory resources and copy strings. Note that the strlen function returns a Valid String Length, excluding the terminator '\ 0 '. The strcpy function is copied together with '\ 0. (4) Step 4: return the reference of this object to implement chained expressions like a = B = C. Do not write the return * this error as return this. Can it be written as return other? Isn't the same effect? No! Because we do not know the lifecycle of the parameter Other. It is possible that other is a temporary object, and it disappears immediately after the assignment is complete, then return other will return garbage. Lazy way to deal with copy constructor and assignment functionWhat if we really don't want to write a copy constructor and a value assignment function, and do not allow others to use the default function generated by the compiler? The method of laziness is to declare the copy constructor and the value assignment function as a private function without writing code. Example: Class {... PRIVATE: A (const A & A); // private copy constructor A & operate = (const A & A); // Private value assignment function }; if someone tries to write the following program: a B (a); // calls the private copy constructor B = A; // the compiler that calls the private value assignment function will indicate an error, because the outside world cannot operate a's private function. Note: The above example may not be compiled in VC, because the keyword is not operate, but operator. 3. When writing a value assignment function for a derived class, do not forget to assign a value to the data member of the base class.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.