Copy constructor, heavy-duty assignment operators of classes, deep copy and shortest copy

Source: Internet
Author: User

1. First, it is clear that the compiler will generate a copy constructor and the overload value assignment operator for us without being defined, this shows that these two functions are an essential part of a class. If a class does not define anything, the compiler will also help us generate the following four functions: 1. A constructor, 2. destructor, 3. copy constructor, 4. overload the value assignment operator.

2. Default copy constructor
The bitwise copy (Shortest copy) between objects is the same as the overloaded value assignment operator, that is, the values in objects are completely copied to another object. In some cases, the member variables in the class need to dynamically open up the heap memory. If bit copy is implemented, the values in the object are completely copied to another object, such as a = B. If a member variable pointer in B has applied for memory, the member variable in a also points to the same memory. This will lead to two problems: (1) When both A and B use this memory, the data of the other party will be modified. This is not the programmer's intention and is difficult to find errors; (2) when B releases the memory (for example, destructor), the pointer in A is a wild pointer and a running error occurs.

3. Based on the problem in step 2, you need to rewrite the copy constructor.
And overload value assignment operators.

3.1
When do I need to rewrite it?

In general, we need to manually compile the Destructor classes, both of which require overload copying functions and value assignment operators. Copy constructors, overload assignment operators, and destructor. These three functions are consistent. If one of them needs to be manually defined, the other two must also be defined, generally, manual definitions are required when pointers or pre-related operations exist.

3.2 Example

Class
{
Public:

A ()
{
}
A (int id, char * t_name)
{
_ Id = ID;
Name = new char [strlen (t_name) + 1];
Strcpy (name, t_name );
}
A (const A &)

{

If (name! = NULL)
Delete name;
_ Id = A. _ id;
Len = strlen (A. Name );
Name = new char [Len + 1];
Strcpy (name, A. Name );

}
A & operator = (const A &)
// Note: the reference of the object must be returned here; otherwise, the value disappears immediately after the result is returned!
{
If (name! = NULL)
Delete name;
This-> _ id = A. _ id;
Int Len = strlen (A. Name );
Name = new char [Len + 1];
Strcpy (name, A. Name );
Return * this;
}

~ A ()
{
Cout <"~ Destructor "<Endl;
Delete name;
}

Int _ id;
Char * Name;
};

Int main ()
{
A A (1, "herengang ");
A B;
B =;
}

3.3 resolution

Note1:
Do not pass objects to functions by value. If the object has internal pointers pointing to the dynamically allocated heap memory, do not consider passing the object to the function by value or by reference. Remember: If the function cannot change the state of the parameter object and the state of the target object, use the const modifier.

Note2: Question:
As we all know that class members need to dynamically apply for objects of classes in the heap space, we 'd better overload their assignment functions and copy functions. The copy constructor does not have any return types. The value assignment function can return multiple types, such as void mentioned above, class1 of the class itself, and reference Class &? Q: What are the differences between the return results of these assignment functions?
Answer: 1 if the value assignment function returns void, we know that the only thing we need to note is that it does not support chained value assignment, that is, a = B = C is not allowed!
2. There is a fundamental difference between the returned class object itself and the reference of Class Object!
First, if it returns the class object itself.
A operator = (A &)
{
If (name! = NULL)
Delete name;
This-> _ id = A. _ id;
Int Len = strlen (A. Name );
Name = new char [Len + 1];
Strcpy (name, A. Name );
Return * this;
}
The process is as follows:
Class1 A ("herengnag ");
Class1 B;
B =;
All the seemingly simple assignment operations are as follows:
1. Release the original heap resource of the object.
2. Apply for a new heap space.
3. Copy the source value to the object's heap Space Value
4. Create a temporary object (call the temporary object copy constructor) and return the temporary object
5. When the temporary object ends, call the temporary object destructor to release the temporary object heap memory.
My God is really complicated !!
However, in these steps, if Step 1 does not include the overload copy function, that is, there is no deep copy. When the heap space of the temporary object is released in step 1, the heap space of the target object will be released. In this way, an error occurs when the Destructor is called at the end of scope B of the target object !!
Therefore, if the value assignment operator returns the class object, overload the copy function of the class (for deep copy )!
Second, if the value assignment operator returns an object reference,
A & operator = (A &)
{
If (name! = NULL)
Delete name;
This-> _ id = A. _ id;
Int Len = strlen (A. Name );
Name = new char [Len + 1];
Strcpy (name, A. Name );
Return * this;
}
The process is as follows:
1. Release the heap space occupied by the original object.
1. Apply for a new heap memory
2. Copy the heap memory value of the source object to the new heap memory.
3. Return the reference of the source object.
4. End.
Therefore, if the value assignment operator returns an object reference, it will not call the copy constructor of the class. This is the key to the problem !!

4. Deep copy and light copy

3. The copy constructor is a deep copy. Deep copy and shallow copy can be simply understood as: If a class has resources, when the objects of this class are copied, the resources are re-allocated. This process is a deep copy, and vice versa, if no resources are re-allocated, it is a small copy.

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.