Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to copy the constructor in C++

2025-04-02 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

This article introduces how to copy the constructor in C++. The content is very detailed. Interested friends can use it for reference. I hope it will be helpful to you.

one。 What is a copy constructor

First of all, for ordinary types of objects, copying between them is simple, such as:

The class object is different from the ordinary object, the internal structure of the class object is generally more complex, there are various member variables.

Let's look at a simple example of a class object copy.

Run the program, the screen output 100. From the running results of the above code, we can see that the system allocates memory for object B and completes the replication process with object A. As far as class objects are concerned, the same type of class objects complete the whole replication process by copying the constructor.

Here is an example of how the copy constructor works.

CExample (const CExample& C) is our custom copy constructor. It can be seen that the copy constructor is a special constructor, the name of the function must be the same as the class name, and one of its necessary parameters is a reference variable of this type.

two。 The timing of the copy constructor call

In C++, the following three objects need to call the copy constructor!

1. Object passes in function parameters by passing a value

When g_Fun () is called, the following important steps occur:

(1) when a formal parameter is passed into the .test object, it will first generate a temporary variable, which is called C.

(2)。 Then call the copy constructor to give the value of test to C. The whole two steps are a little similar: CExample C (test)

(3)。 After the execution of g_Fun (), the C object is deconstructed.

two。 Object is returned from the function by passing a value

When the g_Fun () function executes to return, the following important steps occur:

(1)。 First a temporary variable is generated, which is called XXXX.

(2)。 Then call the copy constructor to give the value of temp to XXXX. The whole two steps are a little similar: CExample XXXX (temp)

(3)。 Destruct the temp local variable at the end of the function execution.

(4)。 After g_Fun () is executed, the XXXX object is destructed.

3. Object needs to be initialized by another object

The copy constructor is called in the last two sentences.

three。 Shallow copy and deep copy

1. Default copy constructor

In many cases, when we do not know the copy constructor, it can be done well to pass the object to the function parameter or the function returns the object, because the compiler will automatically generate a copy constructor for us. This is the "default copy constructor", which is very simple and only uses the values of the data members of the "old object" to assign the data members of the "new object" one by one. It generally takes the following form:

Of course, the above code does not need us to write, the compiler will automatically generate for us. But it would be wrong to think that this will solve the problem of copying objects. Let's consider the following code:

This code adds a static member to the previous class in order to count. In the main function, first create the object rect1, output the number of objects at this time, and then use rect1 to copy out the object rect2, and then output the number of objects at this time, according to the understanding, there should be two objects at this time, but when the actual program runs, the output is 1, reflecting only 1 object. In addition, when you destroy an object, because two objects are called to destroy, the class's destructor is called twice, and the counter becomes negative.

To put it bluntly, the copy constructor does not deal with static data members.

The most fundamental reason for these problems is that when the object is copied, the counter is not incremented, so we rewrite the copy constructor as follows:

two。 Shallow copy

The so-called shallow copy means that when the object is copied, only the data members in the object are simply assigned, and the default copy constructor also performs a shallow copy. In most cases, the "shallow copy" already works well, but once the object has dynamic members, the shallow copy will go wrong. Let's consider the following code:

Before the end of this code, a run error occurs. The reason is that the dynamically allocated content is not operated correctly when the object is copied. Let's analyze it:

After running the defined rect1 object, because there is a dynamically allocated statement in the constructor, the memory after execution is roughly as follows:

When you use rect1 to copy rect2, you only assign the member's value because you are performing a shallow copy, so rect1.p = rect2.p, that is, the two pointers point to the same space in the heap, as shown in the following figure:

Of course, this is not what we expected. When the object is destroyed, the destructors of the two objects will be released twice for the same memory space, which is why the error occurs. What we need is not that the two p have the same value, but that the space that the two p points to has the same value. The solution is to use "deep copy".

3. Deep copy

In the case of "deep copy", dynamic members in the object cannot be simply assigned, but space should be dynamically reallocated. For example, the example above should be handled as follows:

At this point, after the object is copied, a rough picture of memory is as follows:

At this point, the p of rect1 and the p of rect2 each point to a section of memory space, but they point to the same space, which is called "deep copy".

3. Prevent default copy from happening

Through the analysis of object replication, we find that object replication mostly occurs during "value passing". Here is a tip to prevent passing by value-declaring a private copy constructor. It is not even necessary to define the copy constructor, because the copy constructor is private, and if the user tries to pass or return this type of object by value or function, he or she will get a compilation error, thus avoiding passing or returning the object by value.

four。 Copy a few details of the constructor

1. Can private member variables be called in the copy constructor?

Answer: I saw this question on the Internet, and I was a little dizzy at that time. At that time, we know from the name that the copy constructor is a special constructor, and it operates on the member variables of its own class, so it is not restricted by private.

two。 Which of the following functions is the copy constructor and why?

Answer: for a class X, if the first argument of a constructor is one of the following:

A) X &

B) const X &

C) volatile X &

D) const volatile X &

And no other parameters or all other parameters have default values, then this function is a copy constructor.

3. Can there be more than one copy constructor in a class?

Answer: there can be more than one copy constructor in a class.

Note that if there is only one copy constructor with an argument of X & in a class, copy initialization cannot be performed with const X or volatile X objects.

If no copy constructor is defined in a class, the compiler automatically generates a default copy constructor.

This default parameter may be either const X (XRV X &) or XRV X (X &), which is chosen by the compiler depending on the context.

About how to copy the constructor in C++ to share here, I hope the above can be of some help to you, can learn more knowledge. If you think the article is good, you can share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report