A detailed description of C + + assignment functions

Source: Internet
Author: User

Assignment function
There is only one assignment function per class
Because not all objects use copy constructors and assignment functions, programmers may be somewhat dismissive of these two functions.
1, if you do not actively write copy constructors and assignment functions, the compiler will automatically generate a "bit copy" of the default function. If the class contains pointer variables, then the two default functions imply an error.
Take the example of two objects, A and B of the class string, assuming that the content of A.m_data is "Hello" and the content of B.m_data is "world".
Assigning A to B now, the "bit copy" of the default assignment function means that b.m_data = A.m_data is executed.
This will cause three errors:
First, B.m_data original memory is not released, resulting in memory leaks;
The second is that B.m_data and A.m_data point to the same piece of memory, and a or b change will affect the other party;
Thirdly, when the object is destroyed, the M_data is released two times.
2, copy constructors and assignment functions are very easy to confuse, often leading to wrong writing and wrong use. A copy constructor is called when an object is created, and an assignment function can only be called by an object that already exists. In the following program, the third statement is similar to the fourth statement, and you can clearly see which one called the copy constructor and which called the assignment function.
String A ("Hello");
String B ("World");
String C = A; The copy constructor is called, preferably C (a);
c = b; An assignment function was called
The third statement in this example has a poor style and should be rewritten as a string C (a) to distinguish it from the fourth statement.
Copy constructors and assignment functions for class string
Copy constructor
string::string (const String &other)
{
int length = strlen (Other.m_data); Allow operation of other private members m_data
m_data = new Char[length+1];
strcpy (M_data, other.m_data);
}
Assignment function
String & string::operator = (const string &other)
{
if (this = = &other)//(1) Check self-assignment
return *this;
delete [] m_data; (2) Release your original memory resources
int length = strlen (Other.m_data); (3) Allocate new memory resources and copy content
m_data = new Char[length+1];
strcpy (M_data, other.m_data);

return *this; (4) Returns a reference to this object
}
The difference between a class string copy constructor and a normal constructor is that there is no need to compare null with a function entry because "reference" cannot be null, and "pointer" can be NULL.
Class string assignment functions are much more complex than constructors and are implemented in four steps:
(1) The first step, check the self-assigned value. You might think that superfluous, someone would be stupid enough to write a = A, such as a self-assignment statement! Not really.   However, indirect self-assignment is still possible, such as//content self-assignment b = A;   ... C = b;   ... a = c;   Address self-Assignment b = &a;   ... a = *b; Perhaps someone will say: "Even if there is self-assignment, I can ignore, a big deal of time to let the object copy themselves, anyway, no error!" "He's really wrong," he said. Look at the second step of the delete, after committing suicide can you copy yourself? Therefore, if self-assignment is found, the function should be terminated immediately. Note If the check self-assignment if statement if (this = = &other) is incorrectly written as if (*this = = other)
(2) The second step, use the Delete to release the original memory resources. If you don't release it now, you'll never get a chance, and it will cause a memory leak.
(3) The third step is to allocate a new memory resource and copy the string. Note that the function strlen returns a valid string length that does not contain the Terminator ' \ S '. The function strcpy is copied together with '/'.
(4) The fourth step returns a reference to this object for the purpose of implementing a chain expression like a = B = c. Be careful not to write return *this as return. Can it be written as return?       Is the effect not the same? No! Because we don't know the lifetime of the parameter other.   It is possible that other is a temporary object that disappears immediately after the assignment, and return will be garbage. Lazy way to handle copy constructors and assignment functions What if we really don't want to write copy constructors and assignment functions, and not allow others to use the compiler-generated default functions?

Related Article

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.