C++ - Detailed Explanation of Copy Constructor

1. Features of copy constructor:

The function name is the same as the type name

Object(const Object& obj)
{
    
    
}

The above parameter needs to be added with "&", the purpose is to prevent infinite construction and form dead recursion.

With const, the purpose is to always refer to, and the value inside cannot be changed

2. Introduce copy construction by example:

Q: How many objects does the following fun function create during the call? (Answer: five)

insert image description here
insert image description here
insert image description here

Adding a reference will reduce the number of object constructions (four times)
insert image description here
. Why should const be added to the fun function in the figure above? In the end plus or not plus const?
If you don't want to change the actual parameter to join const, if you want the formal parameter to change the actual parameter, don't add const. It depends on whether we want to modify the parameters or not.

3 The problem of using a reference to return and not using a reference to return when constructing an object:

3.1 Return without reference:

insert image description here

3.2 Return by reference - receiving a value from a dead address is not reliable:

Returning by reference returns the address of this object
insert image description here
So: the lifetime of the object is not affected by the fun function, you can return it by reference

4. Default copy construction and overloading of the equals operator

When we do not overload the copy constructor and the equal operator, the system will automatically generate a shallow copy.
insert image description here

5. The problem of deep copy and shallow copy

5.1 Repeated destruction caused by shallow copy:

Shallow copy is to directly assign the content of seqade to seqb, and the analysis is as follows:
insert image description here
then seqb.data also only wants the content pointed to by seqa.data, if we destruct seqb when destructing, the content pointed to by seqb.data will be It will be released, and when seqa occurs, there will be a problem of repeatedly destructing the same space and causing an error.

5.2 Shallow copy will cause memory leaks:

The code is as follows: The
insert image description here
insert image description here
memory analysis diagram is as follows:
insert image description here

6. Override copy construction

When we rewrite the copy structure, we will assign the value of seqa to seqb, then seqb will open up a heap space of the same size as seqa, and then copy the contents of the seqa heap to seqb,
insert image description here

7. Summary

Whenever a class is designed as a pointer or designed to point to a kernel-mode object, it is necessary to write its own copy construction and overloading of the equal sign operator.
(pointers, file pointers/threads, semaphores, mutexes)

Guess you like

Origin blog.csdn.net/m0_54355780/article/details/122474441
Recommended